blob: 9e823168e24158901df26ecdbfcc2b48e4fcb6b1 [file] [log] [blame]
Chris Lattner626ab1c2011-04-08 18:02:51 +00001//===-- ExceptionDemo.cpp - An example using llvm Exceptions --------------===//
Garrison Venna2c2f1a2010-02-09 23:22:43 +00002//
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//
Chris Lattner626ab1c2011-04-08 18:02:51 +00008//===----------------------------------------------------------------------===//
Garrison Venna2c2f1a2010-02-09 23:22:43 +00009//
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//
Chris Lattner626ab1c2011-04-08 18:02:51 +000048//===----------------------------------------------------------------------===//
Garrison Venna2c2f1a2010-02-09 23:22:43 +000049
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"
Garrison Venna2c2f1a2010-02-09 23:22:43 +000059#include "llvm/Target/TargetOptions.h"
60#include "llvm/Transforms/Scalar.h"
61#include "llvm/Support/IRBuilder.h"
62#include "llvm/Support/Dwarf.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000063#include "llvm/Support/TargetSelect.h"
Garrison Venna2c2f1a2010-02-09 23:22:43 +000064
Garrison Vennaae66fa2011-09-22 14:07:50 +000065// FIXME: See use of UpgradeExceptionHandling(...) below
66#include "llvm/AutoUpgrade.h"
67
Garrison Venn18bba842011-04-12 12:30:10 +000068// FIXME: Although all systems tested with (Linux, OS X), do not need this
69// header file included. A user on ubuntu reported, undefined symbols
70// for stderr, and fprintf, and the addition of this include fixed the
71// issue for them. Given that LLVM's best practices include the goal
72// of reducing the number of redundant header files included, the
73// correct solution would be to find out why these symbols are not
74// defined for the system in question, and fix the issue by finding out
75// which LLVM header file, if any, would include these symbols.
Garrison Venn2a7d4ad2011-04-11 19:52:49 +000076#include <cstdio>
Garrison Venn18bba842011-04-12 12:30:10 +000077
Garrison Venna2c2f1a2010-02-09 23:22:43 +000078#include <sstream>
Garrison Venna2c2f1a2010-02-09 23:22:43 +000079#include <stdexcept>
80
81
82#ifndef USE_GLOBAL_STR_CONSTS
83#define USE_GLOBAL_STR_CONSTS true
84#endif
85
86// System C++ ABI unwind types from:
87// http://refspecs.freestandards.org/abi-eh-1.21.html
88
89extern "C" {
Chris Lattner626ab1c2011-04-08 18:02:51 +000090
91 typedef enum {
Garrison Venna2c2f1a2010-02-09 23:22:43 +000092 _URC_NO_REASON = 0,
93 _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
94 _URC_FATAL_PHASE2_ERROR = 2,
95 _URC_FATAL_PHASE1_ERROR = 3,
96 _URC_NORMAL_STOP = 4,
97 _URC_END_OF_STACK = 5,
98 _URC_HANDLER_FOUND = 6,
99 _URC_INSTALL_CONTEXT = 7,
100 _URC_CONTINUE_UNWIND = 8
Chris Lattner626ab1c2011-04-08 18:02:51 +0000101 } _Unwind_Reason_Code;
102
103 typedef enum {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000104 _UA_SEARCH_PHASE = 1,
105 _UA_CLEANUP_PHASE = 2,
106 _UA_HANDLER_FRAME = 4,
107 _UA_FORCE_UNWIND = 8,
108 _UA_END_OF_STACK = 16
Chris Lattner626ab1c2011-04-08 18:02:51 +0000109 } _Unwind_Action;
110
111 struct _Unwind_Exception;
112
113 typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
114 struct _Unwind_Exception *);
115
116 struct _Unwind_Exception {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000117 uint64_t exception_class;
118 _Unwind_Exception_Cleanup_Fn exception_cleanup;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000119
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000120 uintptr_t private_1;
121 uintptr_t private_2;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000122
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000123 // @@@ The IA-64 ABI says that this structure must be double-word aligned.
124 // Taking that literally does not make much sense generically. Instead
125 // we provide the maximum alignment required by any type for the machine.
Chris Lattner626ab1c2011-04-08 18:02:51 +0000126 } __attribute__((__aligned__));
127
128 struct _Unwind_Context;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000129 typedef struct _Unwind_Context *_Unwind_Context_t;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000130
Garrison Venn64cfcef2011-04-10 14:06:52 +0000131 extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000132 extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);
133 extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);
134 extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);
135 extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);
136 extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);
137
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000138} // extern "C"
139
140//
141// Example types
142//
143
144/// This is our simplistic type info
145struct OurExceptionType_t {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000146 /// type info type
147 int type;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000148};
149
150
151/// This is our Exception class which relies on a negative offset to calculate
152/// pointers to its instances from pointers to its unwindException member.
153///
154/// Note: The above unwind.h defines struct _Unwind_Exception to be aligned
155/// on a double word boundary. This is necessary to match the standard:
156/// http://refspecs.freestandards.org/abi-eh-1.21.html
157struct OurBaseException_t {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000158 struct OurExceptionType_t type;
159
160 // Note: This is properly aligned in unwind.h
161 struct _Unwind_Exception unwindException;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000162};
163
164
165// Note: Not needed since we are C++
166typedef struct OurBaseException_t OurException;
167typedef struct _Unwind_Exception OurUnwindException;
168
169//
170// Various globals used to support typeinfo and generatted exceptions in
171// general
172//
173
174static std::map<std::string, llvm::Value*> namedValues;
175
176int64_t ourBaseFromUnwindOffset;
177
178const unsigned char ourBaseExcpClassChars[] =
Chris Lattner626ab1c2011-04-08 18:02:51 +0000179{'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000180
181
182static uint64_t ourBaseExceptionClass = 0;
183
184static std::vector<std::string> ourTypeInfoNames;
185static std::map<int, std::string> ourTypeInfoNamesIndex;
186
Garrison Venn64cfcef2011-04-10 14:06:52 +0000187static llvm::StructType *ourTypeInfoType;
188static llvm::StructType *ourExceptionType;
189static llvm::StructType *ourUnwindExceptionType;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000190
Garrison Venn64cfcef2011-04-10 14:06:52 +0000191static llvm::ConstantInt *ourExceptionNotThrownState;
192static llvm::ConstantInt *ourExceptionThrownState;
193static llvm::ConstantInt *ourExceptionCaughtState;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000194
195typedef std::vector<std::string> ArgNames;
Garrison Venn6e6cdd02011-07-11 16:31:53 +0000196typedef std::vector<llvm::Type*> ArgTypes;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000197
198//
199// Code Generation Utilities
200//
201
202/// Utility used to create a function, both declarations and definitions
203/// @param module for module instance
204/// @param retType function return type
205/// @param theArgTypes function's ordered argument types
206/// @param theArgNames function's ordered arguments needed if use of this
207/// function corresponds to a function definition. Use empty
208/// aggregate for function declarations.
209/// @param functName function name
210/// @param linkage function linkage
211/// @param declarationOnly for function declarations
212/// @param isVarArg function uses vararg arguments
213/// @returns function instance
Garrison Venn64cfcef2011-04-10 14:06:52 +0000214llvm::Function *createFunction(llvm::Module &module,
Chris Lattner77613d42011-07-18 04:52:09 +0000215 llvm::Type *retType,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000216 const ArgTypes &theArgTypes,
217 const ArgNames &theArgNames,
218 const std::string &functName,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000219 llvm::GlobalValue::LinkageTypes linkage,
220 bool declarationOnly,
221 bool isVarArg) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000222 llvm::FunctionType *functType =
223 llvm::FunctionType::get(retType, theArgTypes, isVarArg);
224 llvm::Function *ret =
225 llvm::Function::Create(functType, linkage, functName, &module);
226 if (!ret || declarationOnly)
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000227 return(ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000228
229 namedValues.clear();
230 unsigned i = 0;
231 for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
232 i != theArgNames.size();
233 ++argIndex, ++i) {
234
235 argIndex->setName(theArgNames[i]);
236 namedValues[theArgNames[i]] = argIndex;
237 }
238
239 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000240}
241
242
243/// Create an alloca instruction in the entry block of
244/// the parent function. This is used for mutable variables etc.
245/// @param function parent instance
246/// @param varName stack variable name
247/// @param type stack variable type
248/// @param initWith optional constant initialization value
249/// @returns AllocaInst instance
Garrison Venn64cfcef2011-04-10 14:06:52 +0000250static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000251 const std::string &varName,
Chris Lattner77613d42011-07-18 04:52:09 +0000252 llvm::Type *type,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000253 llvm::Constant *initWith = 0) {
254 llvm::BasicBlock &block = function.getEntryBlock();
Chris Lattner626ab1c2011-04-08 18:02:51 +0000255 llvm::IRBuilder<> tmp(&block, block.begin());
Garrison Venn64cfcef2011-04-10 14:06:52 +0000256 llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());
Chris Lattner626ab1c2011-04-08 18:02:51 +0000257
258 if (initWith)
259 tmp.CreateStore(initWith, ret);
260
261 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000262}
263
264
265//
266// Code Generation Utilities End
267//
268
269//
270// Runtime C Library functions
271//
272
273// Note: using an extern "C" block so that static functions can be used
274extern "C" {
275
276// Note: Better ways to decide on bit width
277//
278/// Prints a 32 bit number, according to the format, to stderr.
279/// @param intToPrint integer to print
280/// @param format printf like format to use when printing
Garrison Venn64cfcef2011-04-10 14:06:52 +0000281void print32Int(int intToPrint, const char *format) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000282 if (format) {
283 // Note: No NULL check
284 fprintf(stderr, format, intToPrint);
285 }
286 else {
287 // Note: No NULL check
288 fprintf(stderr, "::print32Int(...):NULL arg.\n");
289 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000290}
291
292
293// Note: Better ways to decide on bit width
294//
295/// Prints a 64 bit number, according to the format, to stderr.
296/// @param intToPrint integer to print
297/// @param format printf like format to use when printing
Garrison Venn64cfcef2011-04-10 14:06:52 +0000298void print64Int(long int intToPrint, const char *format) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000299 if (format) {
300 // Note: No NULL check
301 fprintf(stderr, format, intToPrint);
302 }
303 else {
304 // Note: No NULL check
305 fprintf(stderr, "::print64Int(...):NULL arg.\n");
306 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000307}
308
309
310/// Prints a C string to stderr
311/// @param toPrint string to print
Garrison Venn64cfcef2011-04-10 14:06:52 +0000312void printStr(char *toPrint) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000313 if (toPrint) {
314 fprintf(stderr, "%s", toPrint);
315 }
316 else {
317 fprintf(stderr, "::printStr(...):NULL arg.\n");
318 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000319}
320
321
322/// Deletes the true previosly allocated exception whose address
323/// is calculated from the supplied OurBaseException_t::unwindException
324/// member address. Handles (ignores), NULL pointers.
325/// @param expToDelete exception to delete
Garrison Venn64cfcef2011-04-10 14:06:52 +0000326void deleteOurException(OurUnwindException *expToDelete) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000327#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000328 fprintf(stderr,
329 "deleteOurException(...).\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000330#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000331
332 if (expToDelete &&
333 (expToDelete->exception_class == ourBaseExceptionClass)) {
334
335 free(((char*) expToDelete) + ourBaseFromUnwindOffset);
336 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000337}
338
339
340/// This function is the struct _Unwind_Exception API mandated delete function
341/// used by foreign exception handlers when deleting our exception
342/// (OurException), instances.
343/// @param reason @link http://refspecs.freestandards.org/abi-eh-1.21.html
344/// @unlink
345/// @param expToDelete exception instance to delete
346void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000347 OurUnwindException *expToDelete) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000348#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000349 fprintf(stderr,
350 "deleteFromUnwindOurException(...).\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000351#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000352
353 deleteOurException(expToDelete);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000354}
355
356
357/// Creates (allocates on the heap), an exception (OurException instance),
358/// of the supplied type info type.
359/// @param type type info type
Garrison Venn64cfcef2011-04-10 14:06:52 +0000360OurUnwindException *createOurException(int type) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000361 size_t size = sizeof(OurException);
Garrison Venn64cfcef2011-04-10 14:06:52 +0000362 OurException *ret = (OurException*) memset(malloc(size), 0, size);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000363 (ret->type).type = type;
364 (ret->unwindException).exception_class = ourBaseExceptionClass;
365 (ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
366
367 return(&(ret->unwindException));
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000368}
369
370
371/// Read a uleb128 encoded value and advance pointer
372/// See Variable Length Data in:
373/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
374/// @param data reference variable holding memory pointer to decode from
375/// @returns decoded value
Garrison Venn64cfcef2011-04-10 14:06:52 +0000376static uintptr_t readULEB128(const uint8_t **data) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000377 uintptr_t result = 0;
378 uintptr_t shift = 0;
379 unsigned char byte;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000380 const uint8_t *p = *data;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000381
382 do {
383 byte = *p++;
384 result |= (byte & 0x7f) << shift;
385 shift += 7;
386 }
387 while (byte & 0x80);
388
389 *data = p;
390
391 return result;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000392}
393
394
395/// Read a sleb128 encoded value and advance pointer
396/// See Variable Length Data in:
397/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
398/// @param data reference variable holding memory pointer to decode from
399/// @returns decoded value
Garrison Venn64cfcef2011-04-10 14:06:52 +0000400static uintptr_t readSLEB128(const uint8_t **data) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000401 uintptr_t result = 0;
402 uintptr_t shift = 0;
403 unsigned char byte;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000404 const uint8_t *p = *data;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000405
406 do {
407 byte = *p++;
408 result |= (byte & 0x7f) << shift;
409 shift += 7;
410 }
411 while (byte & 0x80);
412
413 *data = p;
414
415 if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
416 result |= (~0 << shift);
417 }
418
419 return result;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000420}
421
422
423/// Read a pointer encoded value and advance pointer
424/// See Variable Length Data in:
425/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
426/// @param data reference variable holding memory pointer to decode from
427/// @param encoding dwarf encoding type
428/// @returns decoded value
Garrison Venn64cfcef2011-04-10 14:06:52 +0000429static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000430 uintptr_t result = 0;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000431 const uint8_t *p = *data;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000432
433 if (encoding == llvm::dwarf::DW_EH_PE_omit)
434 return(result);
435
436 // first get value
437 switch (encoding & 0x0F) {
438 case llvm::dwarf::DW_EH_PE_absptr:
439 result = *((uintptr_t*)p);
440 p += sizeof(uintptr_t);
441 break;
442 case llvm::dwarf::DW_EH_PE_uleb128:
443 result = readULEB128(&p);
444 break;
445 // Note: This case has not been tested
446 case llvm::dwarf::DW_EH_PE_sleb128:
447 result = readSLEB128(&p);
448 break;
449 case llvm::dwarf::DW_EH_PE_udata2:
450 result = *((uint16_t*)p);
451 p += sizeof(uint16_t);
452 break;
453 case llvm::dwarf::DW_EH_PE_udata4:
454 result = *((uint32_t*)p);
455 p += sizeof(uint32_t);
456 break;
457 case llvm::dwarf::DW_EH_PE_udata8:
458 result = *((uint64_t*)p);
459 p += sizeof(uint64_t);
460 break;
461 case llvm::dwarf::DW_EH_PE_sdata2:
462 result = *((int16_t*)p);
463 p += sizeof(int16_t);
464 break;
465 case llvm::dwarf::DW_EH_PE_sdata4:
466 result = *((int32_t*)p);
467 p += sizeof(int32_t);
468 break;
469 case llvm::dwarf::DW_EH_PE_sdata8:
470 result = *((int64_t*)p);
471 p += sizeof(int64_t);
472 break;
473 default:
474 // not supported
475 abort();
476 break;
477 }
478
479 // then add relative offset
480 switch (encoding & 0x70) {
481 case llvm::dwarf::DW_EH_PE_absptr:
482 // do nothing
483 break;
484 case llvm::dwarf::DW_EH_PE_pcrel:
485 result += (uintptr_t)(*data);
486 break;
487 case llvm::dwarf::DW_EH_PE_textrel:
488 case llvm::dwarf::DW_EH_PE_datarel:
489 case llvm::dwarf::DW_EH_PE_funcrel:
490 case llvm::dwarf::DW_EH_PE_aligned:
491 default:
492 // not supported
493 abort();
494 break;
495 }
496
497 // then apply indirection
498 if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
499 result = *((uintptr_t*)result);
500 }
501
502 *data = p;
503
504 return result;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000505}
506
507
508/// Deals with Dwarf actions matching our type infos
509/// (OurExceptionType_t instances). Returns whether or not a dwarf emitted
510/// action matches the supplied exception type. If such a match succeeds,
511/// the resultAction argument will be set with > 0 index value. Only
512/// corresponding llvm.eh.selector type info arguments, cleanup arguments
513/// are supported. Filters are not supported.
514/// See Variable Length Data in:
515/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
516/// Also see @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
517/// @param resultAction reference variable which will be set with result
518/// @param classInfo our array of type info pointers (to globals)
519/// @param actionEntry index into above type info array or 0 (clean up).
520/// We do not support filters.
521/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
522/// of thrown exception.
523/// @param exceptionObject thrown _Unwind_Exception instance.
524/// @returns whether or not a type info was found. False is returned if only
525/// a cleanup was found
526static bool handleActionValue(int64_t *resultAction,
527 struct OurExceptionType_t **classInfo,
528 uintptr_t actionEntry,
529 uint64_t exceptionClass,
530 struct _Unwind_Exception *exceptionObject) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000531 bool ret = false;
532
533 if (!resultAction ||
534 !exceptionObject ||
535 (exceptionClass != ourBaseExceptionClass))
536 return(ret);
537
Garrison Venn64cfcef2011-04-10 14:06:52 +0000538 struct OurBaseException_t *excp = (struct OurBaseException_t*)
Chris Lattner626ab1c2011-04-08 18:02:51 +0000539 (((char*) exceptionObject) + ourBaseFromUnwindOffset);
540 struct OurExceptionType_t *excpType = &(excp->type);
541 int type = excpType->type;
542
543#ifdef DEBUG
544 fprintf(stderr,
545 "handleActionValue(...): exceptionObject = <%p>, "
546 "excp = <%p>.\n",
547 exceptionObject,
548 excp);
549#endif
550
551 const uint8_t *actionPos = (uint8_t*) actionEntry,
552 *tempActionPos;
553 int64_t typeOffset = 0,
554 actionOffset;
555
556 for (int i = 0; true; ++i) {
557 // Each emitted dwarf action corresponds to a 2 tuple of
558 // type info address offset, and action offset to the next
559 // emitted action.
560 typeOffset = readSLEB128(&actionPos);
561 tempActionPos = actionPos;
562 actionOffset = readSLEB128(&tempActionPos);
563
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000564#ifdef DEBUG
565 fprintf(stderr,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000566 "handleActionValue(...):typeOffset: <%lld>, "
567 "actionOffset: <%lld>.\n",
568 typeOffset,
569 actionOffset);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000570#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000571 assert((typeOffset >= 0) &&
572 "handleActionValue(...):filters are not supported.");
573
574 // Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
575 // argument has been matched.
576 if ((typeOffset > 0) &&
577 (type == (classInfo[-typeOffset])->type)) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000578#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000579 fprintf(stderr,
580 "handleActionValue(...):actionValue <%d> found.\n",
581 i);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000582#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000583 *resultAction = i + 1;
584 ret = true;
585 break;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000586 }
Chris Lattner626ab1c2011-04-08 18:02:51 +0000587
588#ifdef DEBUG
589 fprintf(stderr,
590 "handleActionValue(...):actionValue not found.\n");
591#endif
592 if (!actionOffset)
593 break;
594
595 actionPos += actionOffset;
596 }
597
598 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000599}
600
601
602/// Deals with the Language specific data portion of the emitted dwarf code.
603/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
604/// @param version unsupported (ignored), unwind version
605/// @param lsda language specific data area
606/// @param _Unwind_Action actions minimally supported unwind stage
607/// (forced specifically not supported)
608/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
609/// of thrown exception.
610/// @param exceptionObject thrown _Unwind_Exception instance.
611/// @param context unwind system context
612/// @returns minimally supported unwinding control indicator
613static _Unwind_Reason_Code handleLsda(int version,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000614 const uint8_t *lsda,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000615 _Unwind_Action actions,
616 uint64_t exceptionClass,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000617 struct _Unwind_Exception *exceptionObject,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000618 _Unwind_Context_t context) {
619 _Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
620
621 if (!lsda)
622 return(ret);
623
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000624#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000625 fprintf(stderr,
626 "handleLsda(...):lsda is non-zero.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000627#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000628
629 // Get the current instruction pointer and offset it before next
630 // instruction in the current frame which threw the exception.
631 uintptr_t pc = _Unwind_GetIP(context)-1;
632
633 // Get beginning current frame's code (as defined by the
634 // emitted dwarf code)
635 uintptr_t funcStart = _Unwind_GetRegionStart(context);
636 uintptr_t pcOffset = pc - funcStart;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000637 struct OurExceptionType_t **classInfo = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000638
639 // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
640 // dwarf emission
641
642 // Parse LSDA header.
643 uint8_t lpStartEncoding = *lsda++;
644
645 if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
646 readEncodedPointer(&lsda, lpStartEncoding);
647 }
648
649 uint8_t ttypeEncoding = *lsda++;
650 uintptr_t classInfoOffset;
651
652 if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
653 // Calculate type info locations in emitted dwarf code which
654 // were flagged by type info arguments to llvm.eh.selector
655 // intrinsic
656 classInfoOffset = readULEB128(&lsda);
657 classInfo = (struct OurExceptionType_t**) (lsda + classInfoOffset);
658 }
659
660 // Walk call-site table looking for range that
661 // includes current PC.
662
663 uint8_t callSiteEncoding = *lsda++;
664 uint32_t callSiteTableLength = readULEB128(&lsda);
Garrison Venn64cfcef2011-04-10 14:06:52 +0000665 const uint8_t *callSiteTableStart = lsda;
666 const uint8_t *callSiteTableEnd = callSiteTableStart +
Chris Lattner626ab1c2011-04-08 18:02:51 +0000667 callSiteTableLength;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000668 const uint8_t *actionTableStart = callSiteTableEnd;
669 const uint8_t *callSitePtr = callSiteTableStart;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000670
671 bool foreignException = false;
672
673 while (callSitePtr < callSiteTableEnd) {
674 uintptr_t start = readEncodedPointer(&callSitePtr,
675 callSiteEncoding);
676 uintptr_t length = readEncodedPointer(&callSitePtr,
677 callSiteEncoding);
678 uintptr_t landingPad = readEncodedPointer(&callSitePtr,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000679 callSiteEncoding);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000680
681 // Note: Action value
682 uintptr_t actionEntry = readULEB128(&callSitePtr);
683
684 if (exceptionClass != ourBaseExceptionClass) {
685 // We have been notified of a foreign exception being thrown,
686 // and we therefore need to execute cleanup landing pads
687 actionEntry = 0;
688 foreignException = true;
689 }
690
691 if (landingPad == 0) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000692#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000693 fprintf(stderr,
694 "handleLsda(...): No landing pad found.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000695#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000696
697 continue; // no landing pad for this entry
698 }
699
700 if (actionEntry) {
701 actionEntry += ((uintptr_t) actionTableStart) - 1;
702 }
703 else {
704#ifdef DEBUG
705 fprintf(stderr,
706 "handleLsda(...):No action table found.\n");
707#endif
708 }
709
710 bool exceptionMatched = false;
711
712 if ((start <= pcOffset) && (pcOffset < (start + length))) {
713#ifdef DEBUG
714 fprintf(stderr,
715 "handleLsda(...): Landing pad found.\n");
716#endif
717 int64_t actionValue = 0;
718
719 if (actionEntry) {
Garrison Venn64cfcef2011-04-10 14:06:52 +0000720 exceptionMatched = handleActionValue(&actionValue,
721 classInfo,
722 actionEntry,
723 exceptionClass,
724 exceptionObject);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000725 }
726
727 if (!(actions & _UA_SEARCH_PHASE)) {
728#ifdef DEBUG
729 fprintf(stderr,
730 "handleLsda(...): installed landing pad "
731 "context.\n");
732#endif
733
734 // Found landing pad for the PC.
735 // Set Instruction Pointer to so we re-enter function
736 // at landing pad. The landing pad is created by the
737 // compiler to take two parameters in registers.
738 _Unwind_SetGR(context,
739 __builtin_eh_return_data_regno(0),
740 (uintptr_t)exceptionObject);
741
742 // Note: this virtual register directly corresponds
743 // to the return of the llvm.eh.selector intrinsic
744 if (!actionEntry || !exceptionMatched) {
745 // We indicate cleanup only
746 _Unwind_SetGR(context,
747 __builtin_eh_return_data_regno(1),
748 0);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000749 }
750 else {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000751 // Matched type info index of llvm.eh.selector intrinsic
752 // passed here.
753 _Unwind_SetGR(context,
754 __builtin_eh_return_data_regno(1),
755 actionValue);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000756 }
Chris Lattner626ab1c2011-04-08 18:02:51 +0000757
758 // To execute landing pad set here
759 _Unwind_SetIP(context, funcStart + landingPad);
760 ret = _URC_INSTALL_CONTEXT;
761 }
762 else if (exceptionMatched) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000763#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000764 fprintf(stderr,
765 "handleLsda(...): setting handler found.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000766#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000767 ret = _URC_HANDLER_FOUND;
768 }
769 else {
770 // Note: Only non-clean up handlers are marked as
771 // found. Otherwise the clean up handlers will be
772 // re-found and executed during the clean up
773 // phase.
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000774#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000775 fprintf(stderr,
776 "handleLsda(...): cleanup handler found.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000777#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000778 }
779
780 break;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000781 }
Chris Lattner626ab1c2011-04-08 18:02:51 +0000782 }
783
784 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000785}
786
787
788/// This is the personality function which is embedded (dwarf emitted), in the
789/// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
790/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
791/// @param version unsupported (ignored), unwind version
792/// @param _Unwind_Action actions minimally supported unwind stage
793/// (forced specifically not supported)
794/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
795/// of thrown exception.
796/// @param exceptionObject thrown _Unwind_Exception instance.
797/// @param context unwind system context
798/// @returns minimally supported unwinding control indicator
799_Unwind_Reason_Code ourPersonality(int version,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000800 _Unwind_Action actions,
801 uint64_t exceptionClass,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000802 struct _Unwind_Exception *exceptionObject,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000803 _Unwind_Context_t context) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000804#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000805 fprintf(stderr,
806 "We are in ourPersonality(...):actions is <%d>.\n",
807 actions);
808
809 if (actions & _UA_SEARCH_PHASE) {
810 fprintf(stderr, "ourPersonality(...):In search phase.\n");
811 }
812 else {
813 fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
814 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000815#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000816
Garrison Venn64cfcef2011-04-10 14:06:52 +0000817 const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000818
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000819#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000820 fprintf(stderr,
821 "ourPersonality(...):lsda = <%p>.\n",
822 lsda);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000823#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000824
825 // The real work of the personality function is captured here
826 return(handleLsda(version,
827 lsda,
828 actions,
829 exceptionClass,
830 exceptionObject,
831 context));
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000832}
833
834
835/// Generates our _Unwind_Exception class from a given character array.
836/// thereby handling arbitrary lengths (not in standard), and handling
837/// embedded \0s.
838/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
839/// @param classChars char array to encode. NULL values not checkedf
840/// @param classCharsSize number of chars in classChars. Value is not checked.
841/// @returns class value
842uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
843{
Chris Lattner626ab1c2011-04-08 18:02:51 +0000844 uint64_t ret = classChars[0];
845
846 for (unsigned i = 1; i < classCharsSize; ++i) {
847 ret <<= 8;
848 ret += classChars[i];
849 }
850
851 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000852}
853
854} // extern "C"
855
856//
857// Runtime C Library functions End
858//
859
860//
861// Code generation functions
862//
863
864/// Generates code to print given constant string
865/// @param context llvm context
866/// @param module code for module instance
867/// @param builder builder instance
868/// @param toPrint string to print
869/// @param useGlobal A value of true (default) indicates a GlobalValue is
870/// generated, and is used to hold the constant string. A value of
871/// false indicates that the constant string will be stored on the
872/// stack.
Garrison Venn64cfcef2011-04-10 14:06:52 +0000873void generateStringPrint(llvm::LLVMContext &context,
874 llvm::Module &module,
875 llvm::IRBuilder<> &builder,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000876 std::string toPrint,
877 bool useGlobal = true) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000878 llvm::Function *printFunct = module.getFunction("printStr");
879
880 llvm::Value *stringVar;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000881 llvm::Constant *stringConstant =
Chris Lattner626ab1c2011-04-08 18:02:51 +0000882 llvm::ConstantArray::get(context, toPrint);
883
884 if (useGlobal) {
885 // Note: Does not work without allocation
886 stringVar =
887 new llvm::GlobalVariable(module,
888 stringConstant->getType(),
889 true,
890 llvm::GlobalValue::LinkerPrivateLinkage,
891 stringConstant,
892 "");
893 }
894 else {
895 stringVar = builder.CreateAlloca(stringConstant->getType());
896 builder.CreateStore(stringConstant, stringVar);
897 }
898
Garrison Venn64cfcef2011-04-10 14:06:52 +0000899 llvm::Value *cast =
Chris Lattner626ab1c2011-04-08 18:02:51 +0000900 builder.CreatePointerCast(stringVar,
Garrison Vennc0f33cb2011-07-12 15:34:42 +0000901 builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +0000902 builder.CreateCall(printFunct, cast);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000903}
904
905
906/// Generates code to print given runtime integer according to constant
907/// string format, and a given print function.
908/// @param context llvm context
909/// @param module code for module instance
910/// @param builder builder instance
911/// @param printFunct function used to "print" integer
912/// @param toPrint string to print
913/// @param format printf like formating string for print
914/// @param useGlobal A value of true (default) indicates a GlobalValue is
915/// generated, and is used to hold the constant string. A value of
916/// false indicates that the constant string will be stored on the
917/// stack.
Garrison Venn64cfcef2011-04-10 14:06:52 +0000918void generateIntegerPrint(llvm::LLVMContext &context,
919 llvm::Module &module,
920 llvm::IRBuilder<> &builder,
921 llvm::Function &printFunct,
922 llvm::Value &toPrint,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000923 std::string format,
924 bool useGlobal = true) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000925 llvm::Constant *stringConstant = llvm::ConstantArray::get(context, format);
926 llvm::Value *stringVar;
927
928 if (useGlobal) {
929 // Note: Does not seem to work without allocation
930 stringVar =
931 new llvm::GlobalVariable(module,
932 stringConstant->getType(),
933 true,
934 llvm::GlobalValue::LinkerPrivateLinkage,
935 stringConstant,
936 "");
937 }
938 else {
939 stringVar = builder.CreateAlloca(stringConstant->getType());
940 builder.CreateStore(stringConstant, stringVar);
941 }
942
Garrison Venn64cfcef2011-04-10 14:06:52 +0000943 llvm::Value *cast =
Chris Lattner626ab1c2011-04-08 18:02:51 +0000944 builder.CreateBitCast(stringVar,
Garrison Vennc0f33cb2011-07-12 15:34:42 +0000945 builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +0000946 builder.CreateCall2(&printFunct, &toPrint, cast);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000947}
948
949
950/// Generates code to handle finally block type semantics: always runs
951/// regardless of whether a thrown exception is passing through or the
952/// parent function is simply exiting. In addition to printing some state
953/// to stderr, this code will resume the exception handling--runs the
954/// unwind resume block, if the exception has not been previously caught
955/// by a catch clause, and will otherwise execute the end block (terminator
956/// block). In addition this function creates the corresponding function's
957/// stack storage for the exception pointer and catch flag status.
958/// @param context llvm context
959/// @param module code for module instance
960/// @param builder builder instance
961/// @param toAddTo parent function to add block to
962/// @param blockName block name of new "finally" block.
963/// @param functionId output id used for printing
964/// @param terminatorBlock terminator "end" block
965/// @param unwindResumeBlock unwind resume block
966/// @param exceptionCaughtFlag reference exception caught/thrown status storage
967/// @param exceptionStorage reference to exception pointer storage
968/// @returns newly created block
Garrison Venn64cfcef2011-04-10 14:06:52 +0000969static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context,
970 llvm::Module &module,
971 llvm::IRBuilder<> &builder,
972 llvm::Function &toAddTo,
973 std::string &blockName,
974 std::string &functionId,
975 llvm::BasicBlock &terminatorBlock,
976 llvm::BasicBlock &unwindResumeBlock,
977 llvm::Value **exceptionCaughtFlag,
978 llvm::Value **exceptionStorage) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000979 assert(exceptionCaughtFlag &&
980 "ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
981 "is NULL");
982 assert(exceptionStorage &&
983 "ExceptionDemo::createFinallyBlock(...):exceptionStorage "
984 "is NULL");
985
986 *exceptionCaughtFlag =
987 createEntryBlockAlloca(toAddTo,
988 "exceptionCaught",
989 ourExceptionNotThrownState->getType(),
990 ourExceptionNotThrownState);
991
Chris Lattner77613d42011-07-18 04:52:09 +0000992 llvm::PointerType *exceptionStorageType = builder.getInt8PtrTy();
Chris Lattner626ab1c2011-04-08 18:02:51 +0000993 *exceptionStorage =
994 createEntryBlockAlloca(toAddTo,
995 "exceptionStorage",
996 exceptionStorageType,
997 llvm::ConstantPointerNull::get(
998 exceptionStorageType));
999
1000 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1001 blockName,
1002 &toAddTo);
1003
1004 builder.SetInsertPoint(ret);
1005
1006 std::ostringstream bufferToPrint;
1007 bufferToPrint << "Gen: Executing finally block "
1008 << blockName << " in " << functionId << "\n";
1009 generateStringPrint(context,
1010 module,
1011 builder,
1012 bufferToPrint.str(),
1013 USE_GLOBAL_STR_CONSTS);
1014
Garrison Venn64cfcef2011-04-10 14:06:52 +00001015 llvm::SwitchInst *theSwitch =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001016 builder.CreateSwitch(builder.CreateLoad(*exceptionCaughtFlag),
1017 &terminatorBlock,
1018 2);
1019 theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
1020 theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
1021
1022 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001023}
1024
1025
1026/// Generates catch block semantics which print a string to indicate type of
1027/// catch executed, sets an exception caught flag, and executes passed in
1028/// end block (terminator block).
1029/// @param context llvm context
1030/// @param module code for module instance
1031/// @param builder builder instance
1032/// @param toAddTo parent function to add block to
1033/// @param blockName block name of new "catch" block.
1034/// @param functionId output id used for printing
1035/// @param terminatorBlock terminator "end" block
1036/// @param exceptionCaughtFlag exception caught/thrown status
1037/// @returns newly created block
Garrison Venn64cfcef2011-04-10 14:06:52 +00001038static llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context,
1039 llvm::Module &module,
1040 llvm::IRBuilder<> &builder,
1041 llvm::Function &toAddTo,
1042 std::string &blockName,
1043 std::string &functionId,
1044 llvm::BasicBlock &terminatorBlock,
1045 llvm::Value &exceptionCaughtFlag) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001046
1047 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1048 blockName,
1049 &toAddTo);
1050
1051 builder.SetInsertPoint(ret);
1052
1053 std::ostringstream bufferToPrint;
1054 bufferToPrint << "Gen: Executing catch block "
1055 << blockName
1056 << " in "
1057 << functionId
1058 << std::endl;
1059 generateStringPrint(context,
1060 module,
1061 builder,
1062 bufferToPrint.str(),
1063 USE_GLOBAL_STR_CONSTS);
1064 builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
1065 builder.CreateBr(&terminatorBlock);
1066
1067 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001068}
1069
1070
1071/// Generates a function which invokes a function (toInvoke) and, whose
1072/// unwind block will "catch" the type info types correspondingly held in the
1073/// exceptionTypesToCatch argument. If the toInvoke function throws an
1074/// exception which does not match any type info types contained in
1075/// exceptionTypesToCatch, the generated code will call _Unwind_Resume
1076/// with the raised exception. On the other hand the generated code will
1077/// normally exit if the toInvoke function does not throw an exception.
1078/// The generated "finally" block is always run regardless of the cause of
1079/// the generated function exit.
1080/// The generated function is returned after being verified.
1081/// @param module code for module instance
1082/// @param builder builder instance
1083/// @param fpm a function pass manager holding optional IR to IR
1084/// transformations
1085/// @param toInvoke inner function to invoke
1086/// @param ourId id used to printing purposes
1087/// @param numExceptionsToCatch length of exceptionTypesToCatch array
1088/// @param exceptionTypesToCatch array of type info types to "catch"
1089/// @returns generated function
1090static
Garrison Venn64cfcef2011-04-10 14:06:52 +00001091llvm::Function *createCatchWrappedInvokeFunction(llvm::Module &module,
1092 llvm::IRBuilder<> &builder,
1093 llvm::FunctionPassManager &fpm,
1094 llvm::Function &toInvoke,
1095 std::string ourId,
1096 unsigned numExceptionsToCatch,
1097 unsigned exceptionTypesToCatch[]) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001098
Garrison Venn64cfcef2011-04-10 14:06:52 +00001099 llvm::LLVMContext &context = module.getContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001100 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1101
1102 ArgTypes argTypes;
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001103 argTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001104
1105 ArgNames argNames;
1106 argNames.push_back("exceptTypeToThrow");
1107
Garrison Venn64cfcef2011-04-10 14:06:52 +00001108 llvm::Function *ret = createFunction(module,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001109 builder.getVoidTy(),
1110 argTypes,
1111 argNames,
1112 ourId,
1113 llvm::Function::ExternalLinkage,
1114 false,
1115 false);
1116
1117 // Block which calls invoke
1118 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1119 "entry",
1120 ret);
1121 // Normal block for invoke
1122 llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,
1123 "normal",
1124 ret);
1125 // Unwind block for invoke
1126 llvm::BasicBlock *exceptionBlock =
1127 llvm::BasicBlock::Create(context, "exception", ret);
1128
1129 // Block which routes exception to correct catch handler block
1130 llvm::BasicBlock *exceptionRouteBlock =
1131 llvm::BasicBlock::Create(context, "exceptionRoute", ret);
1132
1133 // Foreign exception handler
1134 llvm::BasicBlock *externalExceptionBlock =
1135 llvm::BasicBlock::Create(context, "externalException", ret);
1136
1137 // Block which calls _Unwind_Resume
1138 llvm::BasicBlock *unwindResumeBlock =
1139 llvm::BasicBlock::Create(context, "unwindResume", ret);
1140
1141 // Clean up block which delete exception if needed
1142 llvm::BasicBlock *endBlock =
1143 llvm::BasicBlock::Create(context, "end", ret);
1144
1145 std::string nextName;
1146 std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
Garrison Venn64cfcef2011-04-10 14:06:52 +00001147 llvm::Value *exceptionCaughtFlag = NULL;
1148 llvm::Value *exceptionStorage = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +00001149
1150 // Finally block which will branch to unwindResumeBlock if
1151 // exception is not caught. Initializes/allocates stack locations.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001152 llvm::BasicBlock *finallyBlock = createFinallyBlock(context,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001153 module,
1154 builder,
1155 *ret,
1156 nextName = "finally",
1157 ourId,
1158 *endBlock,
1159 *unwindResumeBlock,
1160 &exceptionCaughtFlag,
1161 &exceptionStorage);
1162
1163 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1164 nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
1165
1166 // One catch block per type info to be caught
1167 catchBlocks[i] = createCatchBlock(context,
1168 module,
1169 builder,
1170 *ret,
1171 nextName,
1172 ourId,
1173 *finallyBlock,
1174 *exceptionCaughtFlag);
1175 }
1176
1177 // Entry Block
1178
1179 builder.SetInsertPoint(entryBlock);
1180
1181 std::vector<llvm::Value*> args;
1182 args.push_back(namedValues["exceptTypeToThrow"]);
1183 builder.CreateInvoke(&toInvoke,
1184 normalBlock,
1185 exceptionBlock,
Chris Lattner77613d42011-07-18 04:52:09 +00001186 args);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001187
1188 // End Block
1189
1190 builder.SetInsertPoint(endBlock);
1191
1192 generateStringPrint(context,
1193 module,
1194 builder,
1195 "Gen: In end block: exiting in " + ourId + ".\n",
1196 USE_GLOBAL_STR_CONSTS);
1197 llvm::Function *deleteOurException =
1198 module.getFunction("deleteOurException");
1199
1200 // Note: function handles NULL exceptions
1201 builder.CreateCall(deleteOurException,
1202 builder.CreateLoad(exceptionStorage));
1203 builder.CreateRetVoid();
1204
1205 // Normal Block
1206
1207 builder.SetInsertPoint(normalBlock);
1208
1209 generateStringPrint(context,
1210 module,
1211 builder,
1212 "Gen: No exception in " + ourId + "!\n",
1213 USE_GLOBAL_STR_CONSTS);
1214
1215 // Finally block is always called
1216 builder.CreateBr(finallyBlock);
1217
1218 // Unwind Resume Block
1219
1220 builder.SetInsertPoint(unwindResumeBlock);
1221
1222 llvm::Function *resumeOurException =
1223 module.getFunction("_Unwind_Resume");
1224 builder.CreateCall(resumeOurException,
1225 builder.CreateLoad(exceptionStorage));
1226 builder.CreateUnreachable();
1227
1228 // Exception Block
1229
1230 builder.SetInsertPoint(exceptionBlock);
1231
1232 llvm::Function *ehException = module.getFunction("llvm.eh.exception");
1233
1234 // Retrieve thrown exception
Garrison Venn64cfcef2011-04-10 14:06:52 +00001235 llvm::Value *unwindException = builder.CreateCall(ehException);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001236
1237 // Store exception and flag
1238 builder.CreateStore(unwindException, exceptionStorage);
1239 builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
1240 llvm::Function *personality = module.getFunction("ourPersonality");
Garrison Venn64cfcef2011-04-10 14:06:52 +00001241 llvm::Value *functPtr =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001242 builder.CreatePointerCast(personality,
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001243 builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001244
1245 args.clear();
1246 args.push_back(unwindException);
1247 args.push_back(functPtr);
1248
1249 // Note: Skipping index 0
1250 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1251 // Set up type infos to be caught
1252 args.push_back(module.getGlobalVariable(
1253 ourTypeInfoNames[exceptionTypesToCatch[i]]));
1254 }
1255
1256 args.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), 0));
1257
1258 llvm::Function *ehSelector = module.getFunction("llvm.eh.selector");
1259
1260 // Set up this exeption block as the landing pad which will handle
1261 // given type infos. See case Intrinsic::eh_selector in
1262 // SelectionDAGBuilder::visitIntrinsicCall(...) and AddCatchInfo(...)
1263 // implemented in FunctionLoweringInfo.cpp to see how the implementation
1264 // handles this call. This landing pad (this exception block), will be
1265 // called either because it nees to cleanup (call finally) or a type
1266 // info was found which matched the thrown exception.
Chris Lattner77613d42011-07-18 04:52:09 +00001267 llvm::Value *retTypeInfoIndex = builder.CreateCall(ehSelector, args);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001268
1269 // Retrieve exception_class member from thrown exception
1270 // (_Unwind_Exception instance). This member tells us whether or not
1271 // the exception is foreign.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001272 llvm::Value *unwindExceptionClass =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001273 builder.CreateLoad(builder.CreateStructGEP(
1274 builder.CreatePointerCast(unwindException,
1275 ourUnwindExceptionType->getPointerTo()),
1276 0));
1277
1278 // Branch to the externalExceptionBlock if the exception is foreign or
1279 // to a catch router if not. Either way the finally block will be run.
1280 builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
1281 llvm::ConstantInt::get(builder.getInt64Ty(),
1282 ourBaseExceptionClass)),
1283 exceptionRouteBlock,
1284 externalExceptionBlock);
1285
1286 // External Exception Block
1287
1288 builder.SetInsertPoint(externalExceptionBlock);
1289
1290 generateStringPrint(context,
1291 module,
1292 builder,
1293 "Gen: Foreign exception received.\n",
1294 USE_GLOBAL_STR_CONSTS);
1295
1296 // Branch to the finally block
1297 builder.CreateBr(finallyBlock);
1298
1299 // Exception Route Block
1300
1301 builder.SetInsertPoint(exceptionRouteBlock);
1302
1303 // Casts exception pointer (_Unwind_Exception instance) to parent
1304 // (OurException instance).
1305 //
1306 // Note: ourBaseFromUnwindOffset is usually negative
Garrison Venn64cfcef2011-04-10 14:06:52 +00001307 llvm::Value *typeInfoThrown =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001308 builder.CreatePointerCast(builder.CreateConstGEP1_64(unwindException,
1309 ourBaseFromUnwindOffset),
1310 ourExceptionType->getPointerTo());
1311
1312 // Retrieve thrown exception type info type
1313 //
1314 // Note: Index is not relative to pointer but instead to structure
1315 // unlike a true getelementptr (GEP) instruction
1316 typeInfoThrown = builder.CreateStructGEP(typeInfoThrown, 0);
1317
Garrison Venn64cfcef2011-04-10 14:06:52 +00001318 llvm::Value *typeInfoThrownType =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001319 builder.CreateStructGEP(typeInfoThrown, 0);
1320
1321 generateIntegerPrint(context,
1322 module,
1323 builder,
1324 *toPrint32Int,
1325 *(builder.CreateLoad(typeInfoThrownType)),
1326 "Gen: Exception type <%d> received (stack unwound) "
1327 " in " +
1328 ourId +
1329 ".\n",
1330 USE_GLOBAL_STR_CONSTS);
1331
1332 // Route to matched type info catch block or run cleanup finally block
Garrison Venn64cfcef2011-04-10 14:06:52 +00001333 llvm::SwitchInst *switchToCatchBlock =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001334 builder.CreateSwitch(retTypeInfoIndex,
1335 finallyBlock,
1336 numExceptionsToCatch);
1337
1338 unsigned nextTypeToCatch;
1339
1340 for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
1341 nextTypeToCatch = i - 1;
1342 switchToCatchBlock->addCase(llvm::ConstantInt::get(
1343 llvm::Type::getInt32Ty(context), i),
1344 catchBlocks[nextTypeToCatch]);
1345 }
1346
Garrison Vennaae66fa2011-09-22 14:07:50 +00001347 // FIXME: This is a hack to get the demo working with the new 3.0 exception
1348 // infrastructure. As this makes the demo no longer a demo, and
1349 // especially not a demo on how to use the llvm exception mechanism,
1350 // this hack will shortly be changed to use the new 3.0 exception
1351 // infrastructure. However for the time being this demo is an
1352 // example on how to use the AutoUpgrade UpgradeExceptionHandling(...)
1353 // function on < 3.0 exception handling code.
1354 //
1355 // Must be run before verifier
1356 UpgradeExceptionHandling(&module);
1357
Chris Lattner626ab1c2011-04-08 18:02:51 +00001358 llvm::verifyFunction(*ret);
1359 fpm.run(*ret);
1360
1361 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001362}
1363
1364
1365/// Generates function which throws either an exception matched to a runtime
1366/// determined type info type (argument to generated function), or if this
1367/// runtime value matches nativeThrowType, throws a foreign exception by
1368/// calling nativeThrowFunct.
1369/// @param module code for module instance
1370/// @param builder builder instance
1371/// @param fpm a function pass manager holding optional IR to IR
1372/// transformations
1373/// @param ourId id used to printing purposes
1374/// @param nativeThrowType a runtime argument of this value results in
1375/// nativeThrowFunct being called to generate/throw exception.
1376/// @param nativeThrowFunct function which will throw a foreign exception
1377/// if the above nativeThrowType matches generated function's arg.
1378/// @returns generated function
1379static
Garrison Venn64cfcef2011-04-10 14:06:52 +00001380llvm::Function *createThrowExceptionFunction(llvm::Module &module,
1381 llvm::IRBuilder<> &builder,
1382 llvm::FunctionPassManager &fpm,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001383 std::string ourId,
1384 int32_t nativeThrowType,
Garrison Venn64cfcef2011-04-10 14:06:52 +00001385 llvm::Function &nativeThrowFunct) {
1386 llvm::LLVMContext &context = module.getContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001387 namedValues.clear();
1388 ArgTypes unwindArgTypes;
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001389 unwindArgTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001390 ArgNames unwindArgNames;
1391 unwindArgNames.push_back("exceptTypeToThrow");
1392
1393 llvm::Function *ret = createFunction(module,
1394 builder.getVoidTy(),
1395 unwindArgTypes,
1396 unwindArgNames,
1397 ourId,
1398 llvm::Function::ExternalLinkage,
1399 false,
1400 false);
1401
1402 // Throws either one of our exception or a native C++ exception depending
1403 // on a runtime argument value containing a type info type.
1404 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1405 "entry",
1406 ret);
1407 // Throws a foreign exception
1408 llvm::BasicBlock *nativeThrowBlock =
1409 llvm::BasicBlock::Create(context,
1410 "nativeThrow",
1411 ret);
1412 // Throws one of our Exceptions
1413 llvm::BasicBlock *generatedThrowBlock =
1414 llvm::BasicBlock::Create(context,
1415 "generatedThrow",
1416 ret);
1417 // Retrieved runtime type info type to throw
Garrison Venn64cfcef2011-04-10 14:06:52 +00001418 llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
Chris Lattner626ab1c2011-04-08 18:02:51 +00001419
1420 // nativeThrowBlock block
1421
1422 builder.SetInsertPoint(nativeThrowBlock);
1423
1424 // Throws foreign exception
1425 builder.CreateCall(&nativeThrowFunct, exceptionType);
1426 builder.CreateUnreachable();
1427
1428 // entry block
1429
1430 builder.SetInsertPoint(entryBlock);
1431
1432 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1433 generateIntegerPrint(context,
1434 module,
1435 builder,
1436 *toPrint32Int,
1437 *exceptionType,
1438 "\nGen: About to throw exception type <%d> in " +
1439 ourId +
1440 ".\n",
1441 USE_GLOBAL_STR_CONSTS);
1442
1443 // Switches on runtime type info type value to determine whether or not
1444 // a foreign exception is thrown. Defaults to throwing one of our
1445 // generated exceptions.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001446 llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001447 generatedThrowBlock,
1448 1);
1449
1450 theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),
1451 nativeThrowType),
1452 nativeThrowBlock);
1453
1454 // generatedThrow block
1455
1456 builder.SetInsertPoint(generatedThrowBlock);
1457
1458 llvm::Function *createOurException =
1459 module.getFunction("createOurException");
1460 llvm::Function *raiseOurException =
1461 module.getFunction("_Unwind_RaiseException");
1462
1463 // Creates exception to throw with runtime type info type.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001464 llvm::Value *exception =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001465 builder.CreateCall(createOurException,
1466 namedValues["exceptTypeToThrow"]);
1467
1468 // Throw generated Exception
1469 builder.CreateCall(raiseOurException, exception);
1470 builder.CreateUnreachable();
1471
1472 llvm::verifyFunction(*ret);
1473 fpm.run(*ret);
1474
1475 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001476}
1477
1478static void createStandardUtilityFunctions(unsigned numTypeInfos,
Garrison Venn64cfcef2011-04-10 14:06:52 +00001479 llvm::Module &module,
1480 llvm::IRBuilder<> &builder);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001481
1482/// Creates test code by generating and organizing these functions into the
1483/// test case. The test case consists of an outer function setup to invoke
1484/// an inner function within an environment having multiple catch and single
1485/// finally blocks. This inner function is also setup to invoke a throw
1486/// function within an evironment similar in nature to the outer function's
1487/// catch and finally blocks. Each of these two functions catch mutually
1488/// exclusive subsets (even or odd) of the type info types configured
1489/// for this this. All generated functions have a runtime argument which
1490/// holds a type info type to throw that each function takes and passes it
1491/// to the inner one if such a inner function exists. This type info type is
1492/// looked at by the generated throw function to see whether or not it should
1493/// throw a generated exception with the same type info type, or instead call
1494/// a supplied a function which in turn will throw a foreign exception.
1495/// @param module code for module instance
1496/// @param builder builder instance
1497/// @param fpm a function pass manager holding optional IR to IR
1498/// transformations
1499/// @param nativeThrowFunctName name of external function which will throw
1500/// a foreign exception
1501/// @returns outermost generated test function.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001502llvm::Function *createUnwindExceptionTest(llvm::Module &module,
1503 llvm::IRBuilder<> &builder,
1504 llvm::FunctionPassManager &fpm,
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001505 std::string nativeThrowFunctName) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001506 // Number of type infos to generate
1507 unsigned numTypeInfos = 6;
1508
1509 // Initialze intrisics and external functions to use along with exception
1510 // and type info globals.
1511 createStandardUtilityFunctions(numTypeInfos,
1512 module,
1513 builder);
1514 llvm::Function *nativeThrowFunct =
1515 module.getFunction(nativeThrowFunctName);
1516
1517 // Create exception throw function using the value ~0 to cause
1518 // foreign exceptions to be thrown.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001519 llvm::Function *throwFunct =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001520 createThrowExceptionFunction(module,
1521 builder,
1522 fpm,
1523 "throwFunct",
1524 ~0,
1525 *nativeThrowFunct);
1526 // Inner function will catch even type infos
1527 unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
1528 size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) /
1529 sizeof(unsigned);
1530
1531 // Generate inner function.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001532 llvm::Function *innerCatchFunct =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001533 createCatchWrappedInvokeFunction(module,
1534 builder,
1535 fpm,
1536 *throwFunct,
1537 "innerCatchFunct",
1538 numExceptionTypesToCatch,
1539 innerExceptionTypesToCatch);
1540
1541 // Outer function will catch odd type infos
1542 unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
1543 numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) /
1544 sizeof(unsigned);
1545
1546 // Generate outer function
Garrison Venn64cfcef2011-04-10 14:06:52 +00001547 llvm::Function *outerCatchFunct =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001548 createCatchWrappedInvokeFunction(module,
1549 builder,
1550 fpm,
1551 *innerCatchFunct,
1552 "outerCatchFunct",
1553 numExceptionTypesToCatch,
1554 outerExceptionTypesToCatch);
1555
1556 // Return outer function to run
1557 return(outerCatchFunct);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001558}
1559
1560
1561/// Represents our foreign exceptions
1562class OurCppRunException : public std::runtime_error {
1563public:
Chris Lattner626ab1c2011-04-08 18:02:51 +00001564 OurCppRunException(const std::string reason) :
1565 std::runtime_error(reason) {}
1566
Garrison Venn64cfcef2011-04-10 14:06:52 +00001567 OurCppRunException (const OurCppRunException &toCopy) :
Chris Lattner626ab1c2011-04-08 18:02:51 +00001568 std::runtime_error(toCopy) {}
1569
Garrison Venn64cfcef2011-04-10 14:06:52 +00001570 OurCppRunException &operator = (const OurCppRunException &toCopy) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001571 return(reinterpret_cast<OurCppRunException&>(
1572 std::runtime_error::operator=(toCopy)));
1573 }
1574
1575 ~OurCppRunException (void) throw () {}
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001576};
1577
1578
1579/// Throws foreign C++ exception.
1580/// @param ignoreIt unused parameter that allows function to match implied
1581/// generated function contract.
1582extern "C"
1583void throwCppException (int32_t ignoreIt) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001584 throw(OurCppRunException("thrown by throwCppException(...)"));
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001585}
1586
1587typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
1588
1589/// This is a test harness which runs test by executing generated
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001590/// function with a type info type to throw. Harness wraps the execution
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001591/// of generated function in a C++ try catch clause.
1592/// @param engine execution engine to use for executing generated function.
1593/// This demo program expects this to be a JIT instance for demo
1594/// purposes.
1595/// @param function generated test function to run
1596/// @param typeToThrow type info type of generated exception to throw, or
1597/// indicator to cause foreign exception to be thrown.
1598static
Garrison Venn64cfcef2011-04-10 14:06:52 +00001599void runExceptionThrow(llvm::ExecutionEngine *engine,
1600 llvm::Function *function,
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001601 int32_t typeToThrow) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001602
1603 // Find test's function pointer
1604 OurExceptionThrowFunctType functPtr =
1605 reinterpret_cast<OurExceptionThrowFunctType>(
1606 reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
1607
1608 try {
1609 // Run test
1610 (*functPtr)(typeToThrow);
1611 }
1612 catch (OurCppRunException exc) {
1613 // Catch foreign C++ exception
1614 fprintf(stderr,
1615 "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
1616 "with reason: %s.\n",
1617 exc.what());
1618 }
1619 catch (...) {
1620 // Catch all exceptions including our generated ones. I'm not sure
1621 // why this latter functionality should work, as it seems that
1622 // our exceptions should be foreign to C++ (the _Unwind_Exception::
1623 // exception_class should be different from the one used by C++), and
1624 // therefore C++ should ignore the generated exceptions.
1625
1626 fprintf(stderr,
1627 "\nrunExceptionThrow(...):In C++ catch all.\n");
1628 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001629}
1630
1631//
1632// End test functions
1633//
1634
Garrison Venn6e6cdd02011-07-11 16:31:53 +00001635typedef llvm::ArrayRef<llvm::Type*> TypeArray;
Chris Lattnercad3f772011-04-08 17:56:47 +00001636
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001637/// This initialization routine creates type info globals and
1638/// adds external function declarations to module.
1639/// @param numTypeInfos number of linear type info associated type info types
1640/// to create as GlobalVariable instances, starting with the value 1.
1641/// @param module code for module instance
1642/// @param builder builder instance
1643static void createStandardUtilityFunctions(unsigned numTypeInfos,
Garrison Venn64cfcef2011-04-10 14:06:52 +00001644 llvm::Module &module,
1645 llvm::IRBuilder<> &builder) {
Chris Lattnercad3f772011-04-08 17:56:47 +00001646
Garrison Venn64cfcef2011-04-10 14:06:52 +00001647 llvm::LLVMContext &context = module.getContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001648
1649 // Exception initializations
1650
1651 // Setup exception catch state
1652 ourExceptionNotThrownState =
1653 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
1654 ourExceptionThrownState =
1655 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
1656 ourExceptionCaughtState =
1657 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
1658
1659
1660
1661 // Create our type info type
1662 ourTypeInfoType = llvm::StructType::get(context,
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001663 TypeArray(builder.getInt32Ty()));
Chris Lattner626ab1c2011-04-08 18:02:51 +00001664 // Create OurException type
1665 ourExceptionType = llvm::StructType::get(context,
1666 TypeArray(ourTypeInfoType));
1667
1668 // Create portion of _Unwind_Exception type
1669 //
1670 // Note: Declaring only a portion of the _Unwind_Exception struct.
1671 // Does this cause problems?
1672 ourUnwindExceptionType =
Garrison Venn6e6cdd02011-07-11 16:31:53 +00001673 llvm::StructType::get(context,
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001674 TypeArray(builder.getInt64Ty()));
Garrison Venn6e6cdd02011-07-11 16:31:53 +00001675
Chris Lattner626ab1c2011-04-08 18:02:51 +00001676 struct OurBaseException_t dummyException;
1677
1678 // Calculate offset of OurException::unwindException member.
1679 ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -
1680 ((uintptr_t) &(dummyException.unwindException));
1681
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001682#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +00001683 fprintf(stderr,
1684 "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
1685 "= %lld, sizeof(struct OurBaseException_t) - "
1686 "sizeof(struct _Unwind_Exception) = %lu.\n",
1687 ourBaseFromUnwindOffset,
1688 sizeof(struct OurBaseException_t) -
1689 sizeof(struct _Unwind_Exception));
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001690#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +00001691
1692 size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
1693
1694 // Create our _Unwind_Exception::exception_class value
1695 ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
1696
1697 // Type infos
1698
1699 std::string baseStr = "typeInfo", typeInfoName;
1700 std::ostringstream typeInfoNameBuilder;
1701 std::vector<llvm::Constant*> structVals;
1702
1703 llvm::Constant *nextStruct;
Garrison Venn64cfcef2011-04-10 14:06:52 +00001704 llvm::GlobalVariable *nextGlobal = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +00001705
1706 // Generate each type info
1707 //
1708 // Note: First type info is not used.
1709 for (unsigned i = 0; i <= numTypeInfos; ++i) {
1710 structVals.clear();
1711 structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
1712 nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001713
Chris Lattner626ab1c2011-04-08 18:02:51 +00001714 typeInfoNameBuilder.str("");
1715 typeInfoNameBuilder << baseStr << i;
1716 typeInfoName = typeInfoNameBuilder.str();
1717
1718 // Note: Does not seem to work without allocation
1719 nextGlobal =
1720 new llvm::GlobalVariable(module,
1721 ourTypeInfoType,
1722 true,
1723 llvm::GlobalValue::ExternalLinkage,
1724 nextStruct,
1725 typeInfoName);
1726
1727 ourTypeInfoNames.push_back(typeInfoName);
1728 ourTypeInfoNamesIndex[i] = typeInfoName;
1729 }
1730
1731 ArgNames argNames;
1732 ArgTypes argTypes;
Garrison Venn64cfcef2011-04-10 14:06:52 +00001733 llvm::Function *funct = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +00001734
1735 // print32Int
1736
Chris Lattner77613d42011-07-18 04:52:09 +00001737 llvm::Type *retType = builder.getVoidTy();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001738
1739 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001740 argTypes.push_back(builder.getInt32Ty());
1741 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001742
1743 argNames.clear();
1744
1745 createFunction(module,
1746 retType,
1747 argTypes,
1748 argNames,
1749 "print32Int",
1750 llvm::Function::ExternalLinkage,
1751 true,
1752 false);
1753
1754 // print64Int
1755
1756 retType = builder.getVoidTy();
1757
1758 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001759 argTypes.push_back(builder.getInt64Ty());
1760 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001761
1762 argNames.clear();
1763
1764 createFunction(module,
1765 retType,
1766 argTypes,
1767 argNames,
1768 "print64Int",
1769 llvm::Function::ExternalLinkage,
1770 true,
1771 false);
1772
1773 // printStr
1774
1775 retType = builder.getVoidTy();
1776
1777 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001778 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001779
1780 argNames.clear();
1781
1782 createFunction(module,
1783 retType,
1784 argTypes,
1785 argNames,
1786 "printStr",
1787 llvm::Function::ExternalLinkage,
1788 true,
1789 false);
1790
1791 // throwCppException
1792
1793 retType = builder.getVoidTy();
1794
1795 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001796 argTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001797
1798 argNames.clear();
1799
1800 createFunction(module,
1801 retType,
1802 argTypes,
1803 argNames,
1804 "throwCppException",
1805 llvm::Function::ExternalLinkage,
1806 true,
1807 false);
1808
1809 // deleteOurException
1810
1811 retType = builder.getVoidTy();
1812
1813 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001814 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001815
1816 argNames.clear();
1817
1818 createFunction(module,
1819 retType,
1820 argTypes,
1821 argNames,
1822 "deleteOurException",
1823 llvm::Function::ExternalLinkage,
1824 true,
1825 false);
1826
1827 // createOurException
1828
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001829 retType = builder.getInt8PtrTy();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001830
1831 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001832 argTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001833
1834 argNames.clear();
1835
1836 createFunction(module,
1837 retType,
1838 argTypes,
1839 argNames,
1840 "createOurException",
1841 llvm::Function::ExternalLinkage,
1842 true,
1843 false);
1844
1845 // _Unwind_RaiseException
1846
1847 retType = builder.getInt32Ty();
1848
1849 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001850 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001851
1852 argNames.clear();
1853
1854 funct = createFunction(module,
1855 retType,
1856 argTypes,
1857 argNames,
1858 "_Unwind_RaiseException",
1859 llvm::Function::ExternalLinkage,
1860 true,
1861 false);
1862
1863 funct->addFnAttr(llvm::Attribute::NoReturn);
1864
1865 // _Unwind_Resume
1866
1867 retType = builder.getInt32Ty();
1868
1869 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001870 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001871
1872 argNames.clear();
1873
1874 funct = createFunction(module,
1875 retType,
1876 argTypes,
1877 argNames,
1878 "_Unwind_Resume",
1879 llvm::Function::ExternalLinkage,
1880 true,
1881 false);
1882
1883 funct->addFnAttr(llvm::Attribute::NoReturn);
1884
1885 // ourPersonality
1886
1887 retType = builder.getInt32Ty();
1888
1889 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001890 argTypes.push_back(builder.getInt32Ty());
1891 argTypes.push_back(builder.getInt32Ty());
1892 argTypes.push_back(builder.getInt64Ty());
1893 argTypes.push_back(builder.getInt8PtrTy());
1894 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001895
1896 argNames.clear();
1897
1898 createFunction(module,
1899 retType,
1900 argTypes,
1901 argNames,
1902 "ourPersonality",
1903 llvm::Function::ExternalLinkage,
1904 true,
1905 false);
1906
1907 // llvm.eh.selector intrinsic
1908
1909 getDeclaration(&module, llvm::Intrinsic::eh_selector);
1910
1911 // llvm.eh.exception intrinsic
1912
1913 getDeclaration(&module, llvm::Intrinsic::eh_exception);
1914
1915 // llvm.eh.typeid.for intrinsic
1916
1917 getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001918}
1919
1920
Chris Lattner626ab1c2011-04-08 18:02:51 +00001921//===----------------------------------------------------------------------===//
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001922// Main test driver code.
Chris Lattner626ab1c2011-04-08 18:02:51 +00001923//===----------------------------------------------------------------------===//
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001924
1925/// Demo main routine which takes the type info types to throw. A test will
1926/// be run for each given type info type. While type info types with the value
1927/// of -1 will trigger a foreign C++ exception to be thrown; type info types
1928/// <= 6 and >= 1 will be caught by test functions; and type info types > 6
1929/// will result in exceptions which pass through to the test harness. All other
1930/// type info types are not supported and could cause a crash.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001931int main(int argc, char *argv[]) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001932 if (argc == 1) {
1933 fprintf(stderr,
1934 "\nUsage: ExceptionDemo <exception type to throw> "
1935 "[<type 2>...<type n>].\n"
1936 " Each type must have the value of 1 - 6 for "
1937 "generated exceptions to be caught;\n"
1938 " the value -1 for foreign C++ exceptions to be "
1939 "generated and thrown;\n"
1940 " or the values > 6 for exceptions to be ignored.\n"
1941 "\nTry: ExceptionDemo 2 3 7 -1\n"
1942 " for a full test.\n\n");
1943 return(0);
1944 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001945
Chris Lattner626ab1c2011-04-08 18:02:51 +00001946 // If not set, exception handling will not be turned on
1947 llvm::JITExceptionHandling = true;
1948
1949 llvm::InitializeNativeTarget();
Garrison Venn64cfcef2011-04-10 14:06:52 +00001950 llvm::LLVMContext &context = llvm::getGlobalContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001951 llvm::IRBuilder<> theBuilder(context);
1952
1953 // Make the module, which holds all the code.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001954 llvm::Module *module = new llvm::Module("my cool jit", context);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001955
1956 // Build engine with JIT
1957 llvm::EngineBuilder factory(module);
1958 factory.setEngineKind(llvm::EngineKind::JIT);
1959 factory.setAllocateGVsWithCode(false);
Garrison Venn64cfcef2011-04-10 14:06:52 +00001960 llvm::ExecutionEngine *executionEngine = factory.create();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001961
1962 {
1963 llvm::FunctionPassManager fpm(module);
1964
1965 // Set up the optimizer pipeline.
1966 // Start with registering info about how the
1967 // target lays out data structures.
1968 fpm.add(new llvm::TargetData(*executionEngine->getTargetData()));
1969
1970 // Optimizations turned on
1971#ifdef ADD_OPT_PASSES
1972
1973 // Basic AliasAnslysis support for GVN.
1974 fpm.add(llvm::createBasicAliasAnalysisPass());
1975
1976 // Promote allocas to registers.
1977 fpm.add(llvm::createPromoteMemoryToRegisterPass());
1978
1979 // Do simple "peephole" optimizations and bit-twiddling optzns.
1980 fpm.add(llvm::createInstructionCombiningPass());
1981
1982 // Reassociate expressions.
1983 fpm.add(llvm::createReassociatePass());
1984
1985 // Eliminate Common SubExpressions.
1986 fpm.add(llvm::createGVNPass());
1987
1988 // Simplify the control flow graph (deleting unreachable
1989 // blocks, etc).
1990 fpm.add(llvm::createCFGSimplificationPass());
1991#endif // ADD_OPT_PASSES
1992
1993 fpm.doInitialization();
1994
1995 // Generate test code using function throwCppException(...) as
1996 // the function which throws foreign exceptions.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001997 llvm::Function *toRun =
Garrison Vennaae66fa2011-09-22 14:07:50 +00001998 createUnwindExceptionTest(*module,
1999 theBuilder,
2000 fpm,
2001 "throwCppException");
Chris Lattner626ab1c2011-04-08 18:02:51 +00002002
2003 fprintf(stderr, "\nBegin module dump:\n\n");
2004
2005 module->dump();
2006
2007 fprintf(stderr, "\nEnd module dump:\n");
2008
2009 fprintf(stderr, "\n\nBegin Test:\n");
2010
2011 for (int i = 1; i < argc; ++i) {
2012 // Run test for each argument whose value is the exception
2013 // type to throw.
2014 runExceptionThrow(executionEngine,
2015 toRun,
2016 (unsigned) strtoul(argv[i], NULL, 10));
2017 }
2018
2019 fprintf(stderr, "\nEnd Test:\n\n");
2020 }
2021
2022 delete executionEngine;
2023
2024 return 0;
Garrison Venna2c2f1a2010-02-09 23:22:43 +00002025}
2026