blob: cf078bb3f54346308776115d2d1e8082768431c3 [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
Garrison Venn113aa862011-09-28 10:53:56 +000043// type info type of 7 is explained by: example in rules 1.6.4 in
44// http://sourcery.mentor.com/public/cxx-abi/abi-eh.html (v1.22)
Garrison Venna2c2f1a2010-02-09 23:22:43 +000045//
46// This code uses code from the llvm compiler-rt project and the llvm
47// Kaleidoscope project.
48//
Chris Lattner626ab1c2011-04-08 18:02:51 +000049//===----------------------------------------------------------------------===//
Garrison Venna2c2f1a2010-02-09 23:22:43 +000050
51#include "llvm/LLVMContext.h"
52#include "llvm/DerivedTypes.h"
53#include "llvm/ExecutionEngine/ExecutionEngine.h"
54#include "llvm/ExecutionEngine/JIT.h"
55#include "llvm/Module.h"
56#include "llvm/PassManager.h"
57#include "llvm/Intrinsics.h"
58#include "llvm/Analysis/Verifier.h"
59#include "llvm/Target/TargetData.h"
Garrison Venna2c2f1a2010-02-09 23:22:43 +000060#include "llvm/Target/TargetOptions.h"
61#include "llvm/Transforms/Scalar.h"
62#include "llvm/Support/IRBuilder.h"
63#include "llvm/Support/Dwarf.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000064#include "llvm/Support/TargetSelect.h"
Garrison Venna2c2f1a2010-02-09 23:22:43 +000065
Garrison Venn18bba842011-04-12 12:30:10 +000066// FIXME: Although all systems tested with (Linux, OS X), do not need this
67// header file included. A user on ubuntu reported, undefined symbols
68// for stderr, and fprintf, and the addition of this include fixed the
69// issue for them. Given that LLVM's best practices include the goal
70// of reducing the number of redundant header files included, the
71// correct solution would be to find out why these symbols are not
72// defined for the system in question, and fix the issue by finding out
73// which LLVM header file, if any, would include these symbols.
Garrison Venn2a7d4ad2011-04-11 19:52:49 +000074#include <cstdio>
Garrison Venn18bba842011-04-12 12:30:10 +000075
Garrison Venna2c2f1a2010-02-09 23:22:43 +000076#include <sstream>
Garrison Venna2c2f1a2010-02-09 23:22:43 +000077#include <stdexcept>
78
79
80#ifndef USE_GLOBAL_STR_CONSTS
81#define USE_GLOBAL_STR_CONSTS true
82#endif
83
84// System C++ ABI unwind types from:
Garrison Venn113aa862011-09-28 10:53:56 +000085// http://sourcery.mentor.com/public/cxx-abi/abi-eh.html (v1.22)
Garrison Venna2c2f1a2010-02-09 23:22:43 +000086
87extern "C" {
Chris Lattner626ab1c2011-04-08 18:02:51 +000088
89 typedef enum {
Garrison Venna2c2f1a2010-02-09 23:22:43 +000090 _URC_NO_REASON = 0,
91 _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
92 _URC_FATAL_PHASE2_ERROR = 2,
93 _URC_FATAL_PHASE1_ERROR = 3,
94 _URC_NORMAL_STOP = 4,
95 _URC_END_OF_STACK = 5,
96 _URC_HANDLER_FOUND = 6,
97 _URC_INSTALL_CONTEXT = 7,
98 _URC_CONTINUE_UNWIND = 8
Chris Lattner626ab1c2011-04-08 18:02:51 +000099 } _Unwind_Reason_Code;
100
101 typedef enum {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000102 _UA_SEARCH_PHASE = 1,
103 _UA_CLEANUP_PHASE = 2,
104 _UA_HANDLER_FRAME = 4,
105 _UA_FORCE_UNWIND = 8,
106 _UA_END_OF_STACK = 16
Chris Lattner626ab1c2011-04-08 18:02:51 +0000107 } _Unwind_Action;
108
109 struct _Unwind_Exception;
110
111 typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
112 struct _Unwind_Exception *);
113
114 struct _Unwind_Exception {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000115 uint64_t exception_class;
116 _Unwind_Exception_Cleanup_Fn exception_cleanup;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000117
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000118 uintptr_t private_1;
119 uintptr_t private_2;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000120
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000121 // @@@ The IA-64 ABI says that this structure must be double-word aligned.
122 // Taking that literally does not make much sense generically. Instead
123 // we provide the maximum alignment required by any type for the machine.
Chris Lattner626ab1c2011-04-08 18:02:51 +0000124 } __attribute__((__aligned__));
125
126 struct _Unwind_Context;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000127 typedef struct _Unwind_Context *_Unwind_Context_t;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000128
Garrison Venn64cfcef2011-04-10 14:06:52 +0000129 extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000130 extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);
131 extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);
132 extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);
133 extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);
134 extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);
135
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000136} // extern "C"
137
138//
139// Example types
140//
141
142/// This is our simplistic type info
143struct OurExceptionType_t {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000144 /// type info type
145 int type;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000146};
147
148
149/// This is our Exception class which relies on a negative offset to calculate
150/// pointers to its instances from pointers to its unwindException member.
151///
152/// Note: The above unwind.h defines struct _Unwind_Exception to be aligned
153/// on a double word boundary. This is necessary to match the standard:
154/// http://refspecs.freestandards.org/abi-eh-1.21.html
155struct OurBaseException_t {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000156 struct OurExceptionType_t type;
157
158 // Note: This is properly aligned in unwind.h
159 struct _Unwind_Exception unwindException;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000160};
161
162
163// Note: Not needed since we are C++
164typedef struct OurBaseException_t OurException;
165typedef struct _Unwind_Exception OurUnwindException;
166
167//
168// Various globals used to support typeinfo and generatted exceptions in
169// general
170//
171
172static std::map<std::string, llvm::Value*> namedValues;
173
174int64_t ourBaseFromUnwindOffset;
175
176const unsigned char ourBaseExcpClassChars[] =
Chris Lattner626ab1c2011-04-08 18:02:51 +0000177{'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000178
179
180static uint64_t ourBaseExceptionClass = 0;
181
182static std::vector<std::string> ourTypeInfoNames;
183static std::map<int, std::string> ourTypeInfoNamesIndex;
184
Garrison Venn64cfcef2011-04-10 14:06:52 +0000185static llvm::StructType *ourTypeInfoType;
Garrison Venn85500712011-09-22 15:45:14 +0000186static llvm::StructType *ourCaughtResultType;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000187static llvm::StructType *ourExceptionType;
188static llvm::StructType *ourUnwindExceptionType;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000189
Garrison Venn64cfcef2011-04-10 14:06:52 +0000190static llvm::ConstantInt *ourExceptionNotThrownState;
191static llvm::ConstantInt *ourExceptionThrownState;
192static llvm::ConstantInt *ourExceptionCaughtState;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000193
194typedef std::vector<std::string> ArgNames;
Garrison Venn6e6cdd02011-07-11 16:31:53 +0000195typedef std::vector<llvm::Type*> ArgTypes;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000196
197//
198// Code Generation Utilities
199//
200
201/// Utility used to create a function, both declarations and definitions
202/// @param module for module instance
203/// @param retType function return type
204/// @param theArgTypes function's ordered argument types
205/// @param theArgNames function's ordered arguments needed if use of this
206/// function corresponds to a function definition. Use empty
207/// aggregate for function declarations.
208/// @param functName function name
209/// @param linkage function linkage
210/// @param declarationOnly for function declarations
211/// @param isVarArg function uses vararg arguments
212/// @returns function instance
Garrison Venn64cfcef2011-04-10 14:06:52 +0000213llvm::Function *createFunction(llvm::Module &module,
Chris Lattner77613d42011-07-18 04:52:09 +0000214 llvm::Type *retType,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000215 const ArgTypes &theArgTypes,
216 const ArgNames &theArgNames,
217 const std::string &functName,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000218 llvm::GlobalValue::LinkageTypes linkage,
219 bool declarationOnly,
220 bool isVarArg) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000221 llvm::FunctionType *functType =
222 llvm::FunctionType::get(retType, theArgTypes, isVarArg);
223 llvm::Function *ret =
224 llvm::Function::Create(functType, linkage, functName, &module);
225 if (!ret || declarationOnly)
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000226 return(ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000227
228 namedValues.clear();
229 unsigned i = 0;
230 for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
231 i != theArgNames.size();
232 ++argIndex, ++i) {
233
234 argIndex->setName(theArgNames[i]);
235 namedValues[theArgNames[i]] = argIndex;
236 }
237
238 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000239}
240
241
242/// Create an alloca instruction in the entry block of
243/// the parent function. This is used for mutable variables etc.
244/// @param function parent instance
245/// @param varName stack variable name
246/// @param type stack variable type
247/// @param initWith optional constant initialization value
248/// @returns AllocaInst instance
Garrison Venn64cfcef2011-04-10 14:06:52 +0000249static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000250 const std::string &varName,
Chris Lattner77613d42011-07-18 04:52:09 +0000251 llvm::Type *type,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000252 llvm::Constant *initWith = 0) {
253 llvm::BasicBlock &block = function.getEntryBlock();
Chris Lattner626ab1c2011-04-08 18:02:51 +0000254 llvm::IRBuilder<> tmp(&block, block.begin());
Garrison Venn64cfcef2011-04-10 14:06:52 +0000255 llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());
Chris Lattner626ab1c2011-04-08 18:02:51 +0000256
257 if (initWith)
258 tmp.CreateStore(initWith, ret);
259
260 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000261}
262
263
264//
265// Code Generation Utilities End
266//
267
268//
269// Runtime C Library functions
270//
271
272// Note: using an extern "C" block so that static functions can be used
273extern "C" {
274
275// Note: Better ways to decide on bit width
276//
277/// Prints a 32 bit number, according to the format, to stderr.
278/// @param intToPrint integer to print
279/// @param format printf like format to use when printing
Garrison Venn64cfcef2011-04-10 14:06:52 +0000280void print32Int(int intToPrint, const char *format) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000281 if (format) {
282 // Note: No NULL check
283 fprintf(stderr, format, intToPrint);
284 }
285 else {
286 // Note: No NULL check
287 fprintf(stderr, "::print32Int(...):NULL arg.\n");
288 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000289}
290
291
292// Note: Better ways to decide on bit width
293//
294/// Prints a 64 bit number, according to the format, to stderr.
295/// @param intToPrint integer to print
296/// @param format printf like format to use when printing
Garrison Venn64cfcef2011-04-10 14:06:52 +0000297void print64Int(long int intToPrint, const char *format) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000298 if (format) {
299 // Note: No NULL check
300 fprintf(stderr, format, intToPrint);
301 }
302 else {
303 // Note: No NULL check
304 fprintf(stderr, "::print64Int(...):NULL arg.\n");
305 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000306}
307
308
309/// Prints a C string to stderr
310/// @param toPrint string to print
Garrison Venn64cfcef2011-04-10 14:06:52 +0000311void printStr(char *toPrint) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000312 if (toPrint) {
313 fprintf(stderr, "%s", toPrint);
314 }
315 else {
316 fprintf(stderr, "::printStr(...):NULL arg.\n");
317 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000318}
319
320
321/// Deletes the true previosly allocated exception whose address
322/// is calculated from the supplied OurBaseException_t::unwindException
323/// member address. Handles (ignores), NULL pointers.
324/// @param expToDelete exception to delete
Garrison Venn64cfcef2011-04-10 14:06:52 +0000325void deleteOurException(OurUnwindException *expToDelete) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000326#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000327 fprintf(stderr,
328 "deleteOurException(...).\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000329#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000330
331 if (expToDelete &&
332 (expToDelete->exception_class == ourBaseExceptionClass)) {
333
334 free(((char*) expToDelete) + ourBaseFromUnwindOffset);
335 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000336}
337
338
339/// This function is the struct _Unwind_Exception API mandated delete function
340/// used by foreign exception handlers when deleting our exception
341/// (OurException), instances.
342/// @param reason @link http://refspecs.freestandards.org/abi-eh-1.21.html
343/// @unlink
344/// @param expToDelete exception instance to delete
345void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000346 OurUnwindException *expToDelete) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000347#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000348 fprintf(stderr,
349 "deleteFromUnwindOurException(...).\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000350#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000351
352 deleteOurException(expToDelete);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000353}
354
355
356/// Creates (allocates on the heap), an exception (OurException instance),
357/// of the supplied type info type.
358/// @param type type info type
Garrison Venn64cfcef2011-04-10 14:06:52 +0000359OurUnwindException *createOurException(int type) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000360 size_t size = sizeof(OurException);
Garrison Venn64cfcef2011-04-10 14:06:52 +0000361 OurException *ret = (OurException*) memset(malloc(size), 0, size);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000362 (ret->type).type = type;
363 (ret->unwindException).exception_class = ourBaseExceptionClass;
364 (ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
365
366 return(&(ret->unwindException));
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000367}
368
369
370/// Read a uleb128 encoded value and advance pointer
371/// See Variable Length Data in:
372/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
373/// @param data reference variable holding memory pointer to decode from
374/// @returns decoded value
Garrison Venn64cfcef2011-04-10 14:06:52 +0000375static uintptr_t readULEB128(const uint8_t **data) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000376 uintptr_t result = 0;
377 uintptr_t shift = 0;
378 unsigned char byte;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000379 const uint8_t *p = *data;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000380
381 do {
382 byte = *p++;
383 result |= (byte & 0x7f) << shift;
384 shift += 7;
385 }
386 while (byte & 0x80);
387
388 *data = p;
389
390 return result;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000391}
392
393
394/// Read a sleb128 encoded value and advance pointer
395/// See Variable Length Data in:
396/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
397/// @param data reference variable holding memory pointer to decode from
398/// @returns decoded value
Garrison Venn64cfcef2011-04-10 14:06:52 +0000399static uintptr_t readSLEB128(const uint8_t **data) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000400 uintptr_t result = 0;
401 uintptr_t shift = 0;
402 unsigned char byte;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000403 const uint8_t *p = *data;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000404
405 do {
406 byte = *p++;
407 result |= (byte & 0x7f) << shift;
408 shift += 7;
409 }
410 while (byte & 0x80);
411
412 *data = p;
413
414 if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
415 result |= (~0 << shift);
416 }
417
418 return result;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000419}
420
421
422/// Read a pointer encoded value and advance pointer
423/// See Variable Length Data in:
424/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
425/// @param data reference variable holding memory pointer to decode from
426/// @param encoding dwarf encoding type
427/// @returns decoded value
Garrison Venn64cfcef2011-04-10 14:06:52 +0000428static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000429 uintptr_t result = 0;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000430 const uint8_t *p = *data;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000431
432 if (encoding == llvm::dwarf::DW_EH_PE_omit)
433 return(result);
434
435 // first get value
436 switch (encoding & 0x0F) {
437 case llvm::dwarf::DW_EH_PE_absptr:
438 result = *((uintptr_t*)p);
439 p += sizeof(uintptr_t);
440 break;
441 case llvm::dwarf::DW_EH_PE_uleb128:
442 result = readULEB128(&p);
443 break;
444 // Note: This case has not been tested
445 case llvm::dwarf::DW_EH_PE_sleb128:
446 result = readSLEB128(&p);
447 break;
448 case llvm::dwarf::DW_EH_PE_udata2:
449 result = *((uint16_t*)p);
450 p += sizeof(uint16_t);
451 break;
452 case llvm::dwarf::DW_EH_PE_udata4:
453 result = *((uint32_t*)p);
454 p += sizeof(uint32_t);
455 break;
456 case llvm::dwarf::DW_EH_PE_udata8:
457 result = *((uint64_t*)p);
458 p += sizeof(uint64_t);
459 break;
460 case llvm::dwarf::DW_EH_PE_sdata2:
461 result = *((int16_t*)p);
462 p += sizeof(int16_t);
463 break;
464 case llvm::dwarf::DW_EH_PE_sdata4:
465 result = *((int32_t*)p);
466 p += sizeof(int32_t);
467 break;
468 case llvm::dwarf::DW_EH_PE_sdata8:
469 result = *((int64_t*)p);
470 p += sizeof(int64_t);
471 break;
472 default:
473 // not supported
474 abort();
475 break;
476 }
477
478 // then add relative offset
479 switch (encoding & 0x70) {
480 case llvm::dwarf::DW_EH_PE_absptr:
481 // do nothing
482 break;
483 case llvm::dwarf::DW_EH_PE_pcrel:
484 result += (uintptr_t)(*data);
485 break;
486 case llvm::dwarf::DW_EH_PE_textrel:
487 case llvm::dwarf::DW_EH_PE_datarel:
488 case llvm::dwarf::DW_EH_PE_funcrel:
489 case llvm::dwarf::DW_EH_PE_aligned:
490 default:
491 // not supported
492 abort();
493 break;
494 }
495
496 // then apply indirection
497 if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
498 result = *((uintptr_t*)result);
499 }
500
501 *data = p;
502
503 return result;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000504}
505
506
507/// Deals with Dwarf actions matching our type infos
508/// (OurExceptionType_t instances). Returns whether or not a dwarf emitted
509/// action matches the supplied exception type. If such a match succeeds,
510/// the resultAction argument will be set with > 0 index value. Only
511/// corresponding llvm.eh.selector type info arguments, cleanup arguments
512/// are supported. Filters are not supported.
513/// See Variable Length Data in:
514/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
515/// Also see @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
516/// @param resultAction reference variable which will be set with result
517/// @param classInfo our array of type info pointers (to globals)
518/// @param actionEntry index into above type info array or 0 (clean up).
519/// We do not support filters.
520/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
521/// of thrown exception.
522/// @param exceptionObject thrown _Unwind_Exception instance.
523/// @returns whether or not a type info was found. False is returned if only
524/// a cleanup was found
525static bool handleActionValue(int64_t *resultAction,
526 struct OurExceptionType_t **classInfo,
527 uintptr_t actionEntry,
528 uint64_t exceptionClass,
529 struct _Unwind_Exception *exceptionObject) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000530 bool ret = false;
531
532 if (!resultAction ||
533 !exceptionObject ||
534 (exceptionClass != ourBaseExceptionClass))
535 return(ret);
536
Garrison Venn64cfcef2011-04-10 14:06:52 +0000537 struct OurBaseException_t *excp = (struct OurBaseException_t*)
Chris Lattner626ab1c2011-04-08 18:02:51 +0000538 (((char*) exceptionObject) + ourBaseFromUnwindOffset);
539 struct OurExceptionType_t *excpType = &(excp->type);
540 int type = excpType->type;
541
542#ifdef DEBUG
543 fprintf(stderr,
544 "handleActionValue(...): exceptionObject = <%p>, "
545 "excp = <%p>.\n",
546 exceptionObject,
547 excp);
548#endif
549
550 const uint8_t *actionPos = (uint8_t*) actionEntry,
551 *tempActionPos;
552 int64_t typeOffset = 0,
553 actionOffset;
554
555 for (int i = 0; true; ++i) {
556 // Each emitted dwarf action corresponds to a 2 tuple of
557 // type info address offset, and action offset to the next
558 // emitted action.
559 typeOffset = readSLEB128(&actionPos);
560 tempActionPos = actionPos;
561 actionOffset = readSLEB128(&tempActionPos);
562
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000563#ifdef DEBUG
564 fprintf(stderr,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000565 "handleActionValue(...):typeOffset: <%lld>, "
566 "actionOffset: <%lld>.\n",
567 typeOffset,
568 actionOffset);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000569#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000570 assert((typeOffset >= 0) &&
571 "handleActionValue(...):filters are not supported.");
572
573 // Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
574 // argument has been matched.
575 if ((typeOffset > 0) &&
576 (type == (classInfo[-typeOffset])->type)) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000577#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000578 fprintf(stderr,
579 "handleActionValue(...):actionValue <%d> found.\n",
580 i);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000581#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000582 *resultAction = i + 1;
583 ret = true;
584 break;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000585 }
Chris Lattner626ab1c2011-04-08 18:02:51 +0000586
587#ifdef DEBUG
588 fprintf(stderr,
589 "handleActionValue(...):actionValue not found.\n");
590#endif
591 if (!actionOffset)
592 break;
593
594 actionPos += actionOffset;
595 }
596
597 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000598}
599
600
601/// Deals with the Language specific data portion of the emitted dwarf code.
602/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
603/// @param version unsupported (ignored), unwind version
604/// @param lsda language specific data area
605/// @param _Unwind_Action actions minimally supported unwind stage
606/// (forced specifically not supported)
607/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
608/// of thrown exception.
609/// @param exceptionObject thrown _Unwind_Exception instance.
610/// @param context unwind system context
611/// @returns minimally supported unwinding control indicator
612static _Unwind_Reason_Code handleLsda(int version,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000613 const uint8_t *lsda,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000614 _Unwind_Action actions,
615 uint64_t exceptionClass,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000616 struct _Unwind_Exception *exceptionObject,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000617 _Unwind_Context_t context) {
618 _Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
619
620 if (!lsda)
621 return(ret);
622
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000623#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000624 fprintf(stderr,
625 "handleLsda(...):lsda is non-zero.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000626#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000627
628 // Get the current instruction pointer and offset it before next
629 // instruction in the current frame which threw the exception.
630 uintptr_t pc = _Unwind_GetIP(context)-1;
631
632 // Get beginning current frame's code (as defined by the
633 // emitted dwarf code)
634 uintptr_t funcStart = _Unwind_GetRegionStart(context);
635 uintptr_t pcOffset = pc - funcStart;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000636 struct OurExceptionType_t **classInfo = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000637
638 // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
639 // dwarf emission
640
641 // Parse LSDA header.
642 uint8_t lpStartEncoding = *lsda++;
643
644 if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
645 readEncodedPointer(&lsda, lpStartEncoding);
646 }
647
648 uint8_t ttypeEncoding = *lsda++;
649 uintptr_t classInfoOffset;
650
651 if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
652 // Calculate type info locations in emitted dwarf code which
653 // were flagged by type info arguments to llvm.eh.selector
654 // intrinsic
655 classInfoOffset = readULEB128(&lsda);
656 classInfo = (struct OurExceptionType_t**) (lsda + classInfoOffset);
657 }
658
659 // Walk call-site table looking for range that
660 // includes current PC.
661
662 uint8_t callSiteEncoding = *lsda++;
663 uint32_t callSiteTableLength = readULEB128(&lsda);
Garrison Venn64cfcef2011-04-10 14:06:52 +0000664 const uint8_t *callSiteTableStart = lsda;
665 const uint8_t *callSiteTableEnd = callSiteTableStart +
Chris Lattner626ab1c2011-04-08 18:02:51 +0000666 callSiteTableLength;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000667 const uint8_t *actionTableStart = callSiteTableEnd;
668 const uint8_t *callSitePtr = callSiteTableStart;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000669
670 bool foreignException = false;
671
672 while (callSitePtr < callSiteTableEnd) {
673 uintptr_t start = readEncodedPointer(&callSitePtr,
674 callSiteEncoding);
675 uintptr_t length = readEncodedPointer(&callSitePtr,
676 callSiteEncoding);
677 uintptr_t landingPad = readEncodedPointer(&callSitePtr,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000678 callSiteEncoding);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000679
680 // Note: Action value
681 uintptr_t actionEntry = readULEB128(&callSitePtr);
682
683 if (exceptionClass != ourBaseExceptionClass) {
684 // We have been notified of a foreign exception being thrown,
685 // and we therefore need to execute cleanup landing pads
686 actionEntry = 0;
687 foreignException = true;
688 }
689
690 if (landingPad == 0) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000691#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000692 fprintf(stderr,
693 "handleLsda(...): No landing pad found.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000694#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000695
696 continue; // no landing pad for this entry
697 }
698
699 if (actionEntry) {
700 actionEntry += ((uintptr_t) actionTableStart) - 1;
701 }
702 else {
703#ifdef DEBUG
704 fprintf(stderr,
705 "handleLsda(...):No action table found.\n");
706#endif
707 }
708
709 bool exceptionMatched = false;
710
711 if ((start <= pcOffset) && (pcOffset < (start + length))) {
712#ifdef DEBUG
713 fprintf(stderr,
714 "handleLsda(...): Landing pad found.\n");
715#endif
716 int64_t actionValue = 0;
717
718 if (actionEntry) {
Garrison Venn64cfcef2011-04-10 14:06:52 +0000719 exceptionMatched = handleActionValue(&actionValue,
720 classInfo,
721 actionEntry,
722 exceptionClass,
723 exceptionObject);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000724 }
725
726 if (!(actions & _UA_SEARCH_PHASE)) {
727#ifdef DEBUG
728 fprintf(stderr,
729 "handleLsda(...): installed landing pad "
730 "context.\n");
731#endif
732
733 // Found landing pad for the PC.
734 // Set Instruction Pointer to so we re-enter function
735 // at landing pad. The landing pad is created by the
736 // compiler to take two parameters in registers.
737 _Unwind_SetGR(context,
738 __builtin_eh_return_data_regno(0),
739 (uintptr_t)exceptionObject);
740
741 // Note: this virtual register directly corresponds
742 // to the return of the llvm.eh.selector intrinsic
743 if (!actionEntry || !exceptionMatched) {
744 // We indicate cleanup only
745 _Unwind_SetGR(context,
746 __builtin_eh_return_data_regno(1),
747 0);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000748 }
749 else {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000750 // Matched type info index of llvm.eh.selector intrinsic
751 // passed here.
752 _Unwind_SetGR(context,
753 __builtin_eh_return_data_regno(1),
754 actionValue);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000755 }
Chris Lattner626ab1c2011-04-08 18:02:51 +0000756
757 // To execute landing pad set here
758 _Unwind_SetIP(context, funcStart + landingPad);
759 ret = _URC_INSTALL_CONTEXT;
760 }
761 else if (exceptionMatched) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000762#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000763 fprintf(stderr,
764 "handleLsda(...): setting handler found.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000765#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000766 ret = _URC_HANDLER_FOUND;
767 }
768 else {
769 // Note: Only non-clean up handlers are marked as
770 // found. Otherwise the clean up handlers will be
771 // re-found and executed during the clean up
772 // phase.
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000773#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000774 fprintf(stderr,
775 "handleLsda(...): cleanup handler found.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000776#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000777 }
778
779 break;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000780 }
Chris Lattner626ab1c2011-04-08 18:02:51 +0000781 }
782
783 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000784}
785
786
787/// This is the personality function which is embedded (dwarf emitted), in the
788/// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
789/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
790/// @param version unsupported (ignored), unwind version
791/// @param _Unwind_Action actions minimally supported unwind stage
792/// (forced specifically not supported)
793/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
794/// of thrown exception.
795/// @param exceptionObject thrown _Unwind_Exception instance.
796/// @param context unwind system context
797/// @returns minimally supported unwinding control indicator
798_Unwind_Reason_Code ourPersonality(int version,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000799 _Unwind_Action actions,
800 uint64_t exceptionClass,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000801 struct _Unwind_Exception *exceptionObject,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000802 _Unwind_Context_t context) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000803#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000804 fprintf(stderr,
805 "We are in ourPersonality(...):actions is <%d>.\n",
806 actions);
807
808 if (actions & _UA_SEARCH_PHASE) {
809 fprintf(stderr, "ourPersonality(...):In search phase.\n");
810 }
811 else {
812 fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
813 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000814#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000815
Garrison Venn64cfcef2011-04-10 14:06:52 +0000816 const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000817
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000818#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000819 fprintf(stderr,
820 "ourPersonality(...):lsda = <%p>.\n",
821 lsda);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000822#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000823
824 // The real work of the personality function is captured here
825 return(handleLsda(version,
826 lsda,
827 actions,
828 exceptionClass,
829 exceptionObject,
830 context));
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000831}
832
833
834/// Generates our _Unwind_Exception class from a given character array.
835/// thereby handling arbitrary lengths (not in standard), and handling
836/// embedded \0s.
837/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
838/// @param classChars char array to encode. NULL values not checkedf
839/// @param classCharsSize number of chars in classChars. Value is not checked.
840/// @returns class value
841uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
842{
Chris Lattner626ab1c2011-04-08 18:02:51 +0000843 uint64_t ret = classChars[0];
844
845 for (unsigned i = 1; i < classCharsSize; ++i) {
846 ret <<= 8;
847 ret += classChars[i];
848 }
849
850 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000851}
852
853} // extern "C"
854
855//
856// Runtime C Library functions End
857//
858
859//
860// Code generation functions
861//
862
863/// Generates code to print given constant string
864/// @param context llvm context
865/// @param module code for module instance
866/// @param builder builder instance
867/// @param toPrint string to print
868/// @param useGlobal A value of true (default) indicates a GlobalValue is
869/// generated, and is used to hold the constant string. A value of
870/// false indicates that the constant string will be stored on the
871/// stack.
Garrison Venn64cfcef2011-04-10 14:06:52 +0000872void generateStringPrint(llvm::LLVMContext &context,
873 llvm::Module &module,
874 llvm::IRBuilder<> &builder,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000875 std::string toPrint,
876 bool useGlobal = true) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000877 llvm::Function *printFunct = module.getFunction("printStr");
878
879 llvm::Value *stringVar;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000880 llvm::Constant *stringConstant =
Peter Collingbourne793a32d2012-02-06 14:09:13 +0000881 llvm::ConstantDataArray::getString(context, toPrint);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000882
883 if (useGlobal) {
884 // Note: Does not work without allocation
885 stringVar =
886 new llvm::GlobalVariable(module,
887 stringConstant->getType(),
888 true,
889 llvm::GlobalValue::LinkerPrivateLinkage,
890 stringConstant,
891 "");
892 }
893 else {
894 stringVar = builder.CreateAlloca(stringConstant->getType());
895 builder.CreateStore(stringConstant, stringVar);
896 }
897
Garrison Venn9cb50862011-09-23 14:45:10 +0000898 llvm::Value *cast = builder.CreatePointerCast(stringVar,
899 builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +0000900 builder.CreateCall(printFunct, cast);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000901}
902
903
904/// Generates code to print given runtime integer according to constant
905/// string format, and a given print function.
906/// @param context llvm context
907/// @param module code for module instance
908/// @param builder builder instance
909/// @param printFunct function used to "print" integer
910/// @param toPrint string to print
911/// @param format printf like formating string for print
912/// @param useGlobal A value of true (default) indicates a GlobalValue is
913/// generated, and is used to hold the constant string. A value of
914/// false indicates that the constant string will be stored on the
915/// stack.
Garrison Venn64cfcef2011-04-10 14:06:52 +0000916void generateIntegerPrint(llvm::LLVMContext &context,
917 llvm::Module &module,
918 llvm::IRBuilder<> &builder,
919 llvm::Function &printFunct,
920 llvm::Value &toPrint,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000921 std::string format,
922 bool useGlobal = true) {
Peter Collingbourne793a32d2012-02-06 14:09:13 +0000923 llvm::Constant *stringConstant =
924 llvm::ConstantDataArray::getString(context, format);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000925 llvm::Value *stringVar;
926
927 if (useGlobal) {
928 // Note: Does not seem to work without allocation
929 stringVar =
930 new llvm::GlobalVariable(module,
931 stringConstant->getType(),
932 true,
933 llvm::GlobalValue::LinkerPrivateLinkage,
934 stringConstant,
935 "");
936 }
937 else {
938 stringVar = builder.CreateAlloca(stringConstant->getType());
939 builder.CreateStore(stringConstant, stringVar);
940 }
941
Garrison Venn9cb50862011-09-23 14:45:10 +0000942 llvm::Value *cast = builder.CreateBitCast(stringVar,
943 builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +0000944 builder.CreateCall2(&printFunct, &toPrint, cast);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000945}
946
947
948/// Generates code to handle finally block type semantics: always runs
949/// regardless of whether a thrown exception is passing through or the
950/// parent function is simply exiting. In addition to printing some state
951/// to stderr, this code will resume the exception handling--runs the
952/// unwind resume block, if the exception has not been previously caught
953/// by a catch clause, and will otherwise execute the end block (terminator
954/// block). In addition this function creates the corresponding function's
955/// stack storage for the exception pointer and catch flag status.
956/// @param context llvm context
957/// @param module code for module instance
958/// @param builder builder instance
959/// @param toAddTo parent function to add block to
960/// @param blockName block name of new "finally" block.
961/// @param functionId output id used for printing
962/// @param terminatorBlock terminator "end" block
963/// @param unwindResumeBlock unwind resume block
964/// @param exceptionCaughtFlag reference exception caught/thrown status storage
965/// @param exceptionStorage reference to exception pointer storage
Garrison Venn9cb50862011-09-23 14:45:10 +0000966/// @param caughtResultStorage reference to landingpad result storage
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000967/// @returns newly created block
Garrison Venn64cfcef2011-04-10 14:06:52 +0000968static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context,
969 llvm::Module &module,
970 llvm::IRBuilder<> &builder,
971 llvm::Function &toAddTo,
972 std::string &blockName,
973 std::string &functionId,
974 llvm::BasicBlock &terminatorBlock,
975 llvm::BasicBlock &unwindResumeBlock,
976 llvm::Value **exceptionCaughtFlag,
Bill Wendling08e8db42012-02-04 00:29:12 +0000977 llvm::Value **exceptionStorage,
978 llvm::Value **caughtResultStorage) {
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");
Garrison Venn9cb50862011-09-23 14:45:10 +0000985 assert(caughtResultStorage &&
986 "ExceptionDemo::createFinallyBlock(...):caughtResultStorage "
987 "is NULL");
Chris Lattner626ab1c2011-04-08 18:02:51 +0000988
Garrison Venn9cb50862011-09-23 14:45:10 +0000989 *exceptionCaughtFlag = createEntryBlockAlloca(toAddTo,
990 "exceptionCaught",
991 ourExceptionNotThrownState->getType(),
992 ourExceptionNotThrownState);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000993
Chris Lattner77613d42011-07-18 04:52:09 +0000994 llvm::PointerType *exceptionStorageType = builder.getInt8PtrTy();
Garrison Venn9cb50862011-09-23 14:45:10 +0000995 *exceptionStorage = createEntryBlockAlloca(toAddTo,
996 "exceptionStorage",
997 exceptionStorageType,
998 llvm::ConstantPointerNull::get(
999 exceptionStorageType));
Garrison Venn9cb50862011-09-23 14:45:10 +00001000 *caughtResultStorage = createEntryBlockAlloca(toAddTo,
1001 "caughtResultStorage",
1002 ourCaughtResultType,
1003 llvm::ConstantAggregateZero::get(
1004 ourCaughtResultType));
Chris Lattner626ab1c2011-04-08 18:02:51 +00001005
1006 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1007 blockName,
1008 &toAddTo);
1009
1010 builder.SetInsertPoint(ret);
1011
1012 std::ostringstream bufferToPrint;
1013 bufferToPrint << "Gen: Executing finally block "
1014 << blockName << " in " << functionId << "\n";
1015 generateStringPrint(context,
1016 module,
1017 builder,
1018 bufferToPrint.str(),
1019 USE_GLOBAL_STR_CONSTS);
1020
Garrison Venn9cb50862011-09-23 14:45:10 +00001021 llvm::SwitchInst *theSwitch = builder.CreateSwitch(builder.CreateLoad(
1022 *exceptionCaughtFlag),
1023 &terminatorBlock,
1024 2);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001025 theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
1026 theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
1027
1028 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001029}
1030
1031
1032/// Generates catch block semantics which print a string to indicate type of
1033/// catch executed, sets an exception caught flag, and executes passed in
1034/// end block (terminator block).
1035/// @param context llvm context
1036/// @param module code for module instance
1037/// @param builder builder instance
1038/// @param toAddTo parent function to add block to
1039/// @param blockName block name of new "catch" block.
1040/// @param functionId output id used for printing
1041/// @param terminatorBlock terminator "end" block
1042/// @param exceptionCaughtFlag exception caught/thrown status
1043/// @returns newly created block
Garrison Venn64cfcef2011-04-10 14:06:52 +00001044static llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context,
1045 llvm::Module &module,
1046 llvm::IRBuilder<> &builder,
1047 llvm::Function &toAddTo,
1048 std::string &blockName,
1049 std::string &functionId,
1050 llvm::BasicBlock &terminatorBlock,
1051 llvm::Value &exceptionCaughtFlag) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001052
1053 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1054 blockName,
1055 &toAddTo);
1056
1057 builder.SetInsertPoint(ret);
1058
1059 std::ostringstream bufferToPrint;
1060 bufferToPrint << "Gen: Executing catch block "
1061 << blockName
1062 << " in "
1063 << functionId
1064 << std::endl;
1065 generateStringPrint(context,
1066 module,
1067 builder,
1068 bufferToPrint.str(),
1069 USE_GLOBAL_STR_CONSTS);
1070 builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
1071 builder.CreateBr(&terminatorBlock);
1072
1073 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001074}
1075
1076
1077/// Generates a function which invokes a function (toInvoke) and, whose
1078/// unwind block will "catch" the type info types correspondingly held in the
1079/// exceptionTypesToCatch argument. If the toInvoke function throws an
1080/// exception which does not match any type info types contained in
1081/// exceptionTypesToCatch, the generated code will call _Unwind_Resume
1082/// with the raised exception. On the other hand the generated code will
1083/// normally exit if the toInvoke function does not throw an exception.
1084/// The generated "finally" block is always run regardless of the cause of
1085/// the generated function exit.
1086/// The generated function is returned after being verified.
1087/// @param module code for module instance
1088/// @param builder builder instance
1089/// @param fpm a function pass manager holding optional IR to IR
1090/// transformations
1091/// @param toInvoke inner function to invoke
1092/// @param ourId id used to printing purposes
1093/// @param numExceptionsToCatch length of exceptionTypesToCatch array
1094/// @param exceptionTypesToCatch array of type info types to "catch"
1095/// @returns generated function
1096static
Garrison Venn64cfcef2011-04-10 14:06:52 +00001097llvm::Function *createCatchWrappedInvokeFunction(llvm::Module &module,
1098 llvm::IRBuilder<> &builder,
1099 llvm::FunctionPassManager &fpm,
1100 llvm::Function &toInvoke,
1101 std::string ourId,
1102 unsigned numExceptionsToCatch,
1103 unsigned exceptionTypesToCatch[]) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001104
Garrison Venn64cfcef2011-04-10 14:06:52 +00001105 llvm::LLVMContext &context = module.getContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001106 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1107
1108 ArgTypes argTypes;
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001109 argTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001110
1111 ArgNames argNames;
1112 argNames.push_back("exceptTypeToThrow");
1113
Garrison Venn64cfcef2011-04-10 14:06:52 +00001114 llvm::Function *ret = createFunction(module,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001115 builder.getVoidTy(),
1116 argTypes,
1117 argNames,
1118 ourId,
1119 llvm::Function::ExternalLinkage,
1120 false,
1121 false);
1122
1123 // Block which calls invoke
1124 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1125 "entry",
1126 ret);
1127 // Normal block for invoke
1128 llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,
1129 "normal",
1130 ret);
1131 // Unwind block for invoke
Garrison Venn9cb50862011-09-23 14:45:10 +00001132 llvm::BasicBlock *exceptionBlock = llvm::BasicBlock::Create(context,
1133 "exception",
1134 ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001135
1136 // Block which routes exception to correct catch handler block
Garrison Venn9cb50862011-09-23 14:45:10 +00001137 llvm::BasicBlock *exceptionRouteBlock = llvm::BasicBlock::Create(context,
1138 "exceptionRoute",
1139 ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001140
1141 // Foreign exception handler
Garrison Venn9cb50862011-09-23 14:45:10 +00001142 llvm::BasicBlock *externalExceptionBlock = llvm::BasicBlock::Create(context,
1143 "externalException",
1144 ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001145
1146 // Block which calls _Unwind_Resume
Garrison Venn9cb50862011-09-23 14:45:10 +00001147 llvm::BasicBlock *unwindResumeBlock = llvm::BasicBlock::Create(context,
1148 "unwindResume",
1149 ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001150
1151 // Clean up block which delete exception if needed
Garrison Venn9cb50862011-09-23 14:45:10 +00001152 llvm::BasicBlock *endBlock = llvm::BasicBlock::Create(context, "end", ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001153
1154 std::string nextName;
1155 std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
Garrison Venn64cfcef2011-04-10 14:06:52 +00001156 llvm::Value *exceptionCaughtFlag = NULL;
1157 llvm::Value *exceptionStorage = NULL;
Garrison Venn9cb50862011-09-23 14:45:10 +00001158 llvm::Value *caughtResultStorage = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +00001159
1160 // Finally block which will branch to unwindResumeBlock if
1161 // exception is not caught. Initializes/allocates stack locations.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001162 llvm::BasicBlock *finallyBlock = createFinallyBlock(context,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001163 module,
1164 builder,
1165 *ret,
1166 nextName = "finally",
1167 ourId,
1168 *endBlock,
1169 *unwindResumeBlock,
1170 &exceptionCaughtFlag,
Bill Wendling08e8db42012-02-04 00:29:12 +00001171 &exceptionStorage,
1172 &caughtResultStorage
Garrison Venn9cb50862011-09-23 14:45:10 +00001173 );
Chris Lattner626ab1c2011-04-08 18:02:51 +00001174
1175 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1176 nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
1177
1178 // One catch block per type info to be caught
1179 catchBlocks[i] = createCatchBlock(context,
1180 module,
1181 builder,
1182 *ret,
1183 nextName,
1184 ourId,
1185 *finallyBlock,
1186 *exceptionCaughtFlag);
1187 }
1188
1189 // Entry Block
1190
1191 builder.SetInsertPoint(entryBlock);
1192
1193 std::vector<llvm::Value*> args;
1194 args.push_back(namedValues["exceptTypeToThrow"]);
1195 builder.CreateInvoke(&toInvoke,
1196 normalBlock,
1197 exceptionBlock,
Chris Lattner77613d42011-07-18 04:52:09 +00001198 args);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001199
1200 // End Block
1201
1202 builder.SetInsertPoint(endBlock);
1203
1204 generateStringPrint(context,
1205 module,
1206 builder,
1207 "Gen: In end block: exiting in " + ourId + ".\n",
1208 USE_GLOBAL_STR_CONSTS);
Garrison Venn9cb50862011-09-23 14:45:10 +00001209 llvm::Function *deleteOurException = module.getFunction("deleteOurException");
Chris Lattner626ab1c2011-04-08 18:02:51 +00001210
1211 // Note: function handles NULL exceptions
1212 builder.CreateCall(deleteOurException,
1213 builder.CreateLoad(exceptionStorage));
1214 builder.CreateRetVoid();
1215
1216 // Normal Block
1217
1218 builder.SetInsertPoint(normalBlock);
1219
1220 generateStringPrint(context,
1221 module,
1222 builder,
1223 "Gen: No exception in " + ourId + "!\n",
1224 USE_GLOBAL_STR_CONSTS);
1225
1226 // Finally block is always called
1227 builder.CreateBr(finallyBlock);
1228
1229 // Unwind Resume Block
1230
1231 builder.SetInsertPoint(unwindResumeBlock);
1232
Garrison Venn9cb50862011-09-23 14:45:10 +00001233 builder.CreateResume(builder.CreateLoad(caughtResultStorage));
Chris Lattner626ab1c2011-04-08 18:02:51 +00001234
1235 // Exception Block
1236
1237 builder.SetInsertPoint(exceptionBlock);
1238
Garrison Venn85500712011-09-22 15:45:14 +00001239 llvm::Function *personality = module.getFunction("ourPersonality");
Chris Lattner626ab1c2011-04-08 18:02:51 +00001240
Garrison Venn85500712011-09-22 15:45:14 +00001241 llvm::LandingPadInst *caughtResult =
1242 builder.CreateLandingPad(ourCaughtResultType,
1243 personality,
1244 numExceptionsToCatch,
1245 "landingPad");
1246
1247 caughtResult->setCleanup(true);
1248
1249 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1250 // Set up type infos to be caught
1251 caughtResult->addClause(module.getGlobalVariable(
1252 ourTypeInfoNames[exceptionTypesToCatch[i]]));
1253 }
1254
1255 llvm::Value *unwindException = builder.CreateExtractValue(caughtResult, 0);
Garrison Venn9cb50862011-09-23 14:45:10 +00001256 llvm::Value *retTypeInfoIndex = builder.CreateExtractValue(caughtResult, 1);
Garrison Venn85500712011-09-22 15:45:14 +00001257
Garrison Venn9cb50862011-09-23 14:45:10 +00001258 // FIXME: Redundant storage which, beyond utilizing value of
1259 // caughtResultStore for unwindException storage, may be alleviated
1260 // alltogether with a block rearrangement
1261 builder.CreateStore(caughtResult, caughtResultStorage);
Garrison Venn85500712011-09-22 15:45:14 +00001262 builder.CreateStore(unwindException, exceptionStorage);
1263 builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001264
1265 // Retrieve exception_class member from thrown exception
1266 // (_Unwind_Exception instance). This member tells us whether or not
1267 // the exception is foreign.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001268 llvm::Value *unwindExceptionClass =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001269 builder.CreateLoad(builder.CreateStructGEP(
1270 builder.CreatePointerCast(unwindException,
1271 ourUnwindExceptionType->getPointerTo()),
1272 0));
1273
1274 // Branch to the externalExceptionBlock if the exception is foreign or
1275 // to a catch router if not. Either way the finally block will be run.
1276 builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
1277 llvm::ConstantInt::get(builder.getInt64Ty(),
1278 ourBaseExceptionClass)),
1279 exceptionRouteBlock,
1280 externalExceptionBlock);
1281
1282 // External Exception Block
1283
1284 builder.SetInsertPoint(externalExceptionBlock);
1285
1286 generateStringPrint(context,
1287 module,
1288 builder,
1289 "Gen: Foreign exception received.\n",
1290 USE_GLOBAL_STR_CONSTS);
1291
1292 // Branch to the finally block
1293 builder.CreateBr(finallyBlock);
1294
1295 // Exception Route Block
1296
1297 builder.SetInsertPoint(exceptionRouteBlock);
1298
1299 // Casts exception pointer (_Unwind_Exception instance) to parent
1300 // (OurException instance).
1301 //
1302 // Note: ourBaseFromUnwindOffset is usually negative
Garrison Venn9cb50862011-09-23 14:45:10 +00001303 llvm::Value *typeInfoThrown = builder.CreatePointerCast(
1304 builder.CreateConstGEP1_64(unwindException,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001305 ourBaseFromUnwindOffset),
Garrison Venn9cb50862011-09-23 14:45:10 +00001306 ourExceptionType->getPointerTo());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001307
1308 // Retrieve thrown exception type info type
1309 //
1310 // Note: Index is not relative to pointer but instead to structure
1311 // unlike a true getelementptr (GEP) instruction
1312 typeInfoThrown = builder.CreateStructGEP(typeInfoThrown, 0);
1313
Garrison Venn64cfcef2011-04-10 14:06:52 +00001314 llvm::Value *typeInfoThrownType =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001315 builder.CreateStructGEP(typeInfoThrown, 0);
1316
1317 generateIntegerPrint(context,
1318 module,
1319 builder,
1320 *toPrint32Int,
1321 *(builder.CreateLoad(typeInfoThrownType)),
1322 "Gen: Exception type <%d> received (stack unwound) "
1323 " in " +
1324 ourId +
1325 ".\n",
1326 USE_GLOBAL_STR_CONSTS);
1327
1328 // Route to matched type info catch block or run cleanup finally block
Garrison Venn9cb50862011-09-23 14:45:10 +00001329 llvm::SwitchInst *switchToCatchBlock = builder.CreateSwitch(retTypeInfoIndex,
1330 finallyBlock,
1331 numExceptionsToCatch);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001332
1333 unsigned nextTypeToCatch;
1334
1335 for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
1336 nextTypeToCatch = i - 1;
1337 switchToCatchBlock->addCase(llvm::ConstantInt::get(
1338 llvm::Type::getInt32Ty(context), i),
1339 catchBlocks[nextTypeToCatch]);
1340 }
Garrison Vennaae66fa2011-09-22 14:07:50 +00001341
Chris Lattner626ab1c2011-04-08 18:02:51 +00001342 llvm::verifyFunction(*ret);
1343 fpm.run(*ret);
1344
1345 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001346}
1347
1348
1349/// Generates function which throws either an exception matched to a runtime
1350/// determined type info type (argument to generated function), or if this
1351/// runtime value matches nativeThrowType, throws a foreign exception by
1352/// calling nativeThrowFunct.
1353/// @param module code for module instance
1354/// @param builder builder instance
1355/// @param fpm a function pass manager holding optional IR to IR
1356/// transformations
1357/// @param ourId id used to printing purposes
1358/// @param nativeThrowType a runtime argument of this value results in
1359/// nativeThrowFunct being called to generate/throw exception.
1360/// @param nativeThrowFunct function which will throw a foreign exception
1361/// if the above nativeThrowType matches generated function's arg.
1362/// @returns generated function
1363static
Garrison Venn64cfcef2011-04-10 14:06:52 +00001364llvm::Function *createThrowExceptionFunction(llvm::Module &module,
1365 llvm::IRBuilder<> &builder,
1366 llvm::FunctionPassManager &fpm,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001367 std::string ourId,
1368 int32_t nativeThrowType,
Garrison Venn64cfcef2011-04-10 14:06:52 +00001369 llvm::Function &nativeThrowFunct) {
1370 llvm::LLVMContext &context = module.getContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001371 namedValues.clear();
1372 ArgTypes unwindArgTypes;
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001373 unwindArgTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001374 ArgNames unwindArgNames;
1375 unwindArgNames.push_back("exceptTypeToThrow");
1376
1377 llvm::Function *ret = createFunction(module,
1378 builder.getVoidTy(),
1379 unwindArgTypes,
1380 unwindArgNames,
1381 ourId,
1382 llvm::Function::ExternalLinkage,
1383 false,
1384 false);
1385
1386 // Throws either one of our exception or a native C++ exception depending
1387 // on a runtime argument value containing a type info type.
1388 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1389 "entry",
1390 ret);
1391 // Throws a foreign exception
Garrison Venn9cb50862011-09-23 14:45:10 +00001392 llvm::BasicBlock *nativeThrowBlock = llvm::BasicBlock::Create(context,
1393 "nativeThrow",
1394 ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001395 // Throws one of our Exceptions
Garrison Venn9cb50862011-09-23 14:45:10 +00001396 llvm::BasicBlock *generatedThrowBlock = llvm::BasicBlock::Create(context,
1397 "generatedThrow",
1398 ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001399 // Retrieved runtime type info type to throw
Garrison Venn64cfcef2011-04-10 14:06:52 +00001400 llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
Chris Lattner626ab1c2011-04-08 18:02:51 +00001401
1402 // nativeThrowBlock block
1403
1404 builder.SetInsertPoint(nativeThrowBlock);
1405
1406 // Throws foreign exception
1407 builder.CreateCall(&nativeThrowFunct, exceptionType);
1408 builder.CreateUnreachable();
1409
1410 // entry block
1411
1412 builder.SetInsertPoint(entryBlock);
1413
1414 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1415 generateIntegerPrint(context,
1416 module,
1417 builder,
1418 *toPrint32Int,
1419 *exceptionType,
1420 "\nGen: About to throw exception type <%d> in " +
1421 ourId +
1422 ".\n",
1423 USE_GLOBAL_STR_CONSTS);
1424
1425 // Switches on runtime type info type value to determine whether or not
1426 // a foreign exception is thrown. Defaults to throwing one of our
1427 // generated exceptions.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001428 llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001429 generatedThrowBlock,
1430 1);
1431
1432 theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),
1433 nativeThrowType),
1434 nativeThrowBlock);
1435
1436 // generatedThrow block
1437
1438 builder.SetInsertPoint(generatedThrowBlock);
1439
Garrison Venn9cb50862011-09-23 14:45:10 +00001440 llvm::Function *createOurException = module.getFunction("createOurException");
1441 llvm::Function *raiseOurException = module.getFunction(
1442 "_Unwind_RaiseException");
Chris Lattner626ab1c2011-04-08 18:02:51 +00001443
1444 // Creates exception to throw with runtime type info type.
Garrison Venn9cb50862011-09-23 14:45:10 +00001445 llvm::Value *exception = builder.CreateCall(createOurException,
1446 namedValues["exceptTypeToThrow"]);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001447
1448 // Throw generated Exception
1449 builder.CreateCall(raiseOurException, exception);
1450 builder.CreateUnreachable();
1451
1452 llvm::verifyFunction(*ret);
1453 fpm.run(*ret);
1454
1455 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001456}
1457
1458static void createStandardUtilityFunctions(unsigned numTypeInfos,
Garrison Venn64cfcef2011-04-10 14:06:52 +00001459 llvm::Module &module,
1460 llvm::IRBuilder<> &builder);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001461
1462/// Creates test code by generating and organizing these functions into the
1463/// test case. The test case consists of an outer function setup to invoke
1464/// an inner function within an environment having multiple catch and single
1465/// finally blocks. This inner function is also setup to invoke a throw
1466/// function within an evironment similar in nature to the outer function's
1467/// catch and finally blocks. Each of these two functions catch mutually
1468/// exclusive subsets (even or odd) of the type info types configured
1469/// for this this. All generated functions have a runtime argument which
1470/// holds a type info type to throw that each function takes and passes it
1471/// to the inner one if such a inner function exists. This type info type is
1472/// looked at by the generated throw function to see whether or not it should
1473/// throw a generated exception with the same type info type, or instead call
1474/// a supplied a function which in turn will throw a foreign exception.
1475/// @param module code for module instance
1476/// @param builder builder instance
1477/// @param fpm a function pass manager holding optional IR to IR
1478/// transformations
1479/// @param nativeThrowFunctName name of external function which will throw
1480/// a foreign exception
1481/// @returns outermost generated test function.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001482llvm::Function *createUnwindExceptionTest(llvm::Module &module,
1483 llvm::IRBuilder<> &builder,
1484 llvm::FunctionPassManager &fpm,
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001485 std::string nativeThrowFunctName) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001486 // Number of type infos to generate
1487 unsigned numTypeInfos = 6;
1488
1489 // Initialze intrisics and external functions to use along with exception
1490 // and type info globals.
1491 createStandardUtilityFunctions(numTypeInfos,
1492 module,
1493 builder);
Garrison Venn9cb50862011-09-23 14:45:10 +00001494 llvm::Function *nativeThrowFunct = module.getFunction(nativeThrowFunctName);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001495
1496 // Create exception throw function using the value ~0 to cause
1497 // foreign exceptions to be thrown.
Garrison Venn9cb50862011-09-23 14:45:10 +00001498 llvm::Function *throwFunct = createThrowExceptionFunction(module,
1499 builder,
1500 fpm,
1501 "throwFunct",
1502 ~0,
1503 *nativeThrowFunct);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001504 // Inner function will catch even type infos
1505 unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
1506 size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) /
Garrison Venn9cb50862011-09-23 14:45:10 +00001507 sizeof(unsigned);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001508
1509 // Generate inner function.
Garrison Venn9cb50862011-09-23 14:45:10 +00001510 llvm::Function *innerCatchFunct = createCatchWrappedInvokeFunction(module,
1511 builder,
1512 fpm,
1513 *throwFunct,
1514 "innerCatchFunct",
1515 numExceptionTypesToCatch,
1516 innerExceptionTypesToCatch);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001517
1518 // Outer function will catch odd type infos
1519 unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
1520 numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) /
1521 sizeof(unsigned);
1522
1523 // Generate outer function
Garrison Venn9cb50862011-09-23 14:45:10 +00001524 llvm::Function *outerCatchFunct = createCatchWrappedInvokeFunction(module,
1525 builder,
1526 fpm,
1527 *innerCatchFunct,
1528 "outerCatchFunct",
1529 numExceptionTypesToCatch,
1530 outerExceptionTypesToCatch);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001531
1532 // Return outer function to run
1533 return(outerCatchFunct);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001534}
1535
1536
1537/// Represents our foreign exceptions
1538class OurCppRunException : public std::runtime_error {
1539public:
Chris Lattner626ab1c2011-04-08 18:02:51 +00001540 OurCppRunException(const std::string reason) :
1541 std::runtime_error(reason) {}
1542
Garrison Venn64cfcef2011-04-10 14:06:52 +00001543 OurCppRunException (const OurCppRunException &toCopy) :
Chris Lattner626ab1c2011-04-08 18:02:51 +00001544 std::runtime_error(toCopy) {}
1545
Garrison Venn64cfcef2011-04-10 14:06:52 +00001546 OurCppRunException &operator = (const OurCppRunException &toCopy) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001547 return(reinterpret_cast<OurCppRunException&>(
1548 std::runtime_error::operator=(toCopy)));
1549 }
1550
1551 ~OurCppRunException (void) throw () {}
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001552};
1553
1554
1555/// Throws foreign C++ exception.
1556/// @param ignoreIt unused parameter that allows function to match implied
1557/// generated function contract.
1558extern "C"
1559void throwCppException (int32_t ignoreIt) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001560 throw(OurCppRunException("thrown by throwCppException(...)"));
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001561}
1562
1563typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
1564
1565/// This is a test harness which runs test by executing generated
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001566/// function with a type info type to throw. Harness wraps the execution
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001567/// of generated function in a C++ try catch clause.
1568/// @param engine execution engine to use for executing generated function.
1569/// This demo program expects this to be a JIT instance for demo
1570/// purposes.
1571/// @param function generated test function to run
1572/// @param typeToThrow type info type of generated exception to throw, or
1573/// indicator to cause foreign exception to be thrown.
1574static
Garrison Venn64cfcef2011-04-10 14:06:52 +00001575void runExceptionThrow(llvm::ExecutionEngine *engine,
1576 llvm::Function *function,
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001577 int32_t typeToThrow) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001578
1579 // Find test's function pointer
1580 OurExceptionThrowFunctType functPtr =
1581 reinterpret_cast<OurExceptionThrowFunctType>(
1582 reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
1583
1584 try {
1585 // Run test
1586 (*functPtr)(typeToThrow);
1587 }
1588 catch (OurCppRunException exc) {
1589 // Catch foreign C++ exception
1590 fprintf(stderr,
1591 "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
1592 "with reason: %s.\n",
1593 exc.what());
1594 }
1595 catch (...) {
Garrison Venn113aa862011-09-28 10:53:56 +00001596 // Catch all exceptions including our generated ones. This latter
1597 // functionality works according to the example in rules 1.6.4 of
1598 // http://sourcery.mentor.com/public/cxx-abi/abi-eh.html (v1.22),
1599 // given that these will be exceptions foreign to C++
1600 // (the _Unwind_Exception::exception_class should be different from
1601 // the one used by C++).
Chris Lattner626ab1c2011-04-08 18:02:51 +00001602 fprintf(stderr,
1603 "\nrunExceptionThrow(...):In C++ catch all.\n");
1604 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001605}
1606
1607//
1608// End test functions
1609//
1610
Garrison Venn6e6cdd02011-07-11 16:31:53 +00001611typedef llvm::ArrayRef<llvm::Type*> TypeArray;
Chris Lattnercad3f772011-04-08 17:56:47 +00001612
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001613/// This initialization routine creates type info globals and
1614/// adds external function declarations to module.
1615/// @param numTypeInfos number of linear type info associated type info types
1616/// to create as GlobalVariable instances, starting with the value 1.
1617/// @param module code for module instance
1618/// @param builder builder instance
1619static void createStandardUtilityFunctions(unsigned numTypeInfos,
Garrison Venn64cfcef2011-04-10 14:06:52 +00001620 llvm::Module &module,
1621 llvm::IRBuilder<> &builder) {
Chris Lattnercad3f772011-04-08 17:56:47 +00001622
Garrison Venn64cfcef2011-04-10 14:06:52 +00001623 llvm::LLVMContext &context = module.getContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001624
1625 // Exception initializations
1626
1627 // Setup exception catch state
1628 ourExceptionNotThrownState =
Garrison Venn9cb50862011-09-23 14:45:10 +00001629 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
Chris Lattner626ab1c2011-04-08 18:02:51 +00001630 ourExceptionThrownState =
Garrison Venn9cb50862011-09-23 14:45:10 +00001631 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
Chris Lattner626ab1c2011-04-08 18:02:51 +00001632 ourExceptionCaughtState =
Garrison Venn9cb50862011-09-23 14:45:10 +00001633 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
Chris Lattner626ab1c2011-04-08 18:02:51 +00001634
1635
1636
1637 // Create our type info type
1638 ourTypeInfoType = llvm::StructType::get(context,
Garrison Venn9cb50862011-09-23 14:45:10 +00001639 TypeArray(builder.getInt32Ty()));
Garrison Venn85500712011-09-22 15:45:14 +00001640
Garrison Venn85500712011-09-22 15:45:14 +00001641 llvm::Type *caughtResultFieldTypes[] = {
1642 builder.getInt8PtrTy(),
1643 builder.getInt32Ty()
1644 };
1645
1646 // Create our landingpad result type
1647 ourCaughtResultType = llvm::StructType::get(context,
1648 TypeArray(caughtResultFieldTypes));
1649
Chris Lattner626ab1c2011-04-08 18:02:51 +00001650 // Create OurException type
1651 ourExceptionType = llvm::StructType::get(context,
1652 TypeArray(ourTypeInfoType));
1653
1654 // Create portion of _Unwind_Exception type
1655 //
1656 // Note: Declaring only a portion of the _Unwind_Exception struct.
1657 // Does this cause problems?
1658 ourUnwindExceptionType =
Garrison Venn6e6cdd02011-07-11 16:31:53 +00001659 llvm::StructType::get(context,
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001660 TypeArray(builder.getInt64Ty()));
Garrison Venn6e6cdd02011-07-11 16:31:53 +00001661
Chris Lattner626ab1c2011-04-08 18:02:51 +00001662 struct OurBaseException_t dummyException;
1663
1664 // Calculate offset of OurException::unwindException member.
1665 ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -
Garrison Venn9cb50862011-09-23 14:45:10 +00001666 ((uintptr_t) &(dummyException.unwindException));
Chris Lattner626ab1c2011-04-08 18:02:51 +00001667
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001668#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +00001669 fprintf(stderr,
1670 "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
1671 "= %lld, sizeof(struct OurBaseException_t) - "
1672 "sizeof(struct _Unwind_Exception) = %lu.\n",
1673 ourBaseFromUnwindOffset,
1674 sizeof(struct OurBaseException_t) -
1675 sizeof(struct _Unwind_Exception));
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001676#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +00001677
1678 size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
1679
1680 // Create our _Unwind_Exception::exception_class value
1681 ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
1682
1683 // Type infos
1684
1685 std::string baseStr = "typeInfo", typeInfoName;
1686 std::ostringstream typeInfoNameBuilder;
1687 std::vector<llvm::Constant*> structVals;
1688
1689 llvm::Constant *nextStruct;
Garrison Venn64cfcef2011-04-10 14:06:52 +00001690 llvm::GlobalVariable *nextGlobal = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +00001691
1692 // Generate each type info
1693 //
1694 // Note: First type info is not used.
1695 for (unsigned i = 0; i <= numTypeInfos; ++i) {
1696 structVals.clear();
1697 structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
1698 nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001699
Chris Lattner626ab1c2011-04-08 18:02:51 +00001700 typeInfoNameBuilder.str("");
1701 typeInfoNameBuilder << baseStr << i;
1702 typeInfoName = typeInfoNameBuilder.str();
1703
1704 // Note: Does not seem to work without allocation
1705 nextGlobal =
1706 new llvm::GlobalVariable(module,
1707 ourTypeInfoType,
1708 true,
1709 llvm::GlobalValue::ExternalLinkage,
1710 nextStruct,
1711 typeInfoName);
1712
1713 ourTypeInfoNames.push_back(typeInfoName);
1714 ourTypeInfoNamesIndex[i] = typeInfoName;
1715 }
1716
1717 ArgNames argNames;
1718 ArgTypes argTypes;
Garrison Venn64cfcef2011-04-10 14:06:52 +00001719 llvm::Function *funct = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +00001720
1721 // print32Int
1722
Chris Lattner77613d42011-07-18 04:52:09 +00001723 llvm::Type *retType = builder.getVoidTy();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001724
1725 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001726 argTypes.push_back(builder.getInt32Ty());
1727 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001728
1729 argNames.clear();
1730
1731 createFunction(module,
1732 retType,
1733 argTypes,
1734 argNames,
1735 "print32Int",
1736 llvm::Function::ExternalLinkage,
1737 true,
1738 false);
1739
1740 // print64Int
1741
1742 retType = builder.getVoidTy();
1743
1744 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001745 argTypes.push_back(builder.getInt64Ty());
1746 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001747
1748 argNames.clear();
1749
1750 createFunction(module,
1751 retType,
1752 argTypes,
1753 argNames,
1754 "print64Int",
1755 llvm::Function::ExternalLinkage,
1756 true,
1757 false);
1758
1759 // printStr
1760
1761 retType = builder.getVoidTy();
1762
1763 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001764 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001765
1766 argNames.clear();
1767
1768 createFunction(module,
1769 retType,
1770 argTypes,
1771 argNames,
1772 "printStr",
1773 llvm::Function::ExternalLinkage,
1774 true,
1775 false);
1776
1777 // throwCppException
1778
1779 retType = builder.getVoidTy();
1780
1781 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001782 argTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001783
1784 argNames.clear();
1785
1786 createFunction(module,
1787 retType,
1788 argTypes,
1789 argNames,
1790 "throwCppException",
1791 llvm::Function::ExternalLinkage,
1792 true,
1793 false);
1794
1795 // deleteOurException
1796
1797 retType = builder.getVoidTy();
1798
1799 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001800 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001801
1802 argNames.clear();
1803
1804 createFunction(module,
1805 retType,
1806 argTypes,
1807 argNames,
1808 "deleteOurException",
1809 llvm::Function::ExternalLinkage,
1810 true,
1811 false);
1812
1813 // createOurException
1814
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001815 retType = builder.getInt8PtrTy();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001816
1817 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001818 argTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001819
1820 argNames.clear();
1821
1822 createFunction(module,
1823 retType,
1824 argTypes,
1825 argNames,
1826 "createOurException",
1827 llvm::Function::ExternalLinkage,
1828 true,
1829 false);
1830
1831 // _Unwind_RaiseException
1832
1833 retType = builder.getInt32Ty();
1834
1835 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001836 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001837
1838 argNames.clear();
1839
1840 funct = createFunction(module,
1841 retType,
1842 argTypes,
1843 argNames,
1844 "_Unwind_RaiseException",
1845 llvm::Function::ExternalLinkage,
1846 true,
1847 false);
1848
1849 funct->addFnAttr(llvm::Attribute::NoReturn);
1850
1851 // _Unwind_Resume
1852
1853 retType = builder.getInt32Ty();
1854
1855 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001856 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001857
1858 argNames.clear();
1859
1860 funct = createFunction(module,
1861 retType,
1862 argTypes,
1863 argNames,
1864 "_Unwind_Resume",
1865 llvm::Function::ExternalLinkage,
1866 true,
1867 false);
1868
1869 funct->addFnAttr(llvm::Attribute::NoReturn);
1870
1871 // ourPersonality
1872
1873 retType = builder.getInt32Ty();
1874
1875 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001876 argTypes.push_back(builder.getInt32Ty());
1877 argTypes.push_back(builder.getInt32Ty());
1878 argTypes.push_back(builder.getInt64Ty());
1879 argTypes.push_back(builder.getInt8PtrTy());
1880 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001881
1882 argNames.clear();
1883
1884 createFunction(module,
1885 retType,
1886 argTypes,
1887 argNames,
1888 "ourPersonality",
1889 llvm::Function::ExternalLinkage,
1890 true,
1891 false);
1892
Chris Lattner626ab1c2011-04-08 18:02:51 +00001893 // llvm.eh.typeid.for intrinsic
1894
1895 getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001896}
1897
1898
Chris Lattner626ab1c2011-04-08 18:02:51 +00001899//===----------------------------------------------------------------------===//
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001900// Main test driver code.
Chris Lattner626ab1c2011-04-08 18:02:51 +00001901//===----------------------------------------------------------------------===//
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001902
1903/// Demo main routine which takes the type info types to throw. A test will
1904/// be run for each given type info type. While type info types with the value
1905/// of -1 will trigger a foreign C++ exception to be thrown; type info types
1906/// <= 6 and >= 1 will be caught by test functions; and type info types > 6
1907/// will result in exceptions which pass through to the test harness. All other
1908/// type info types are not supported and could cause a crash.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001909int main(int argc, char *argv[]) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001910 if (argc == 1) {
1911 fprintf(stderr,
1912 "\nUsage: ExceptionDemo <exception type to throw> "
1913 "[<type 2>...<type n>].\n"
1914 " Each type must have the value of 1 - 6 for "
1915 "generated exceptions to be caught;\n"
1916 " the value -1 for foreign C++ exceptions to be "
1917 "generated and thrown;\n"
1918 " or the values > 6 for exceptions to be ignored.\n"
1919 "\nTry: ExceptionDemo 2 3 7 -1\n"
1920 " for a full test.\n\n");
1921 return(0);
1922 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001923
Chris Lattner626ab1c2011-04-08 18:02:51 +00001924 // If not set, exception handling will not be turned on
Peter Collingbourned40e1032011-12-07 23:58:57 +00001925 llvm::TargetOptions Opts;
1926 Opts.JITExceptionHandling = true;
Chris Lattner626ab1c2011-04-08 18:02:51 +00001927
1928 llvm::InitializeNativeTarget();
Garrison Venn64cfcef2011-04-10 14:06:52 +00001929 llvm::LLVMContext &context = llvm::getGlobalContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001930 llvm::IRBuilder<> theBuilder(context);
1931
1932 // Make the module, which holds all the code.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001933 llvm::Module *module = new llvm::Module("my cool jit", context);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001934
1935 // Build engine with JIT
1936 llvm::EngineBuilder factory(module);
1937 factory.setEngineKind(llvm::EngineKind::JIT);
1938 factory.setAllocateGVsWithCode(false);
Peter Collingbourned40e1032011-12-07 23:58:57 +00001939 factory.setTargetOptions(Opts);
Garrison Venn64cfcef2011-04-10 14:06:52 +00001940 llvm::ExecutionEngine *executionEngine = factory.create();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001941
1942 {
1943 llvm::FunctionPassManager fpm(module);
1944
1945 // Set up the optimizer pipeline.
1946 // Start with registering info about how the
1947 // target lays out data structures.
1948 fpm.add(new llvm::TargetData(*executionEngine->getTargetData()));
1949
1950 // Optimizations turned on
1951#ifdef ADD_OPT_PASSES
1952
1953 // Basic AliasAnslysis support for GVN.
1954 fpm.add(llvm::createBasicAliasAnalysisPass());
1955
1956 // Promote allocas to registers.
1957 fpm.add(llvm::createPromoteMemoryToRegisterPass());
1958
1959 // Do simple "peephole" optimizations and bit-twiddling optzns.
1960 fpm.add(llvm::createInstructionCombiningPass());
1961
1962 // Reassociate expressions.
1963 fpm.add(llvm::createReassociatePass());
1964
1965 // Eliminate Common SubExpressions.
1966 fpm.add(llvm::createGVNPass());
1967
1968 // Simplify the control flow graph (deleting unreachable
1969 // blocks, etc).
1970 fpm.add(llvm::createCFGSimplificationPass());
1971#endif // ADD_OPT_PASSES
1972
1973 fpm.doInitialization();
1974
1975 // Generate test code using function throwCppException(...) as
1976 // the function which throws foreign exceptions.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001977 llvm::Function *toRun =
Garrison Venn85500712011-09-22 15:45:14 +00001978 createUnwindExceptionTest(*module,
1979 theBuilder,
1980 fpm,
1981 "throwCppException");
Chris Lattner626ab1c2011-04-08 18:02:51 +00001982
1983 fprintf(stderr, "\nBegin module dump:\n\n");
1984
1985 module->dump();
1986
1987 fprintf(stderr, "\nEnd module dump:\n");
1988
1989 fprintf(stderr, "\n\nBegin Test:\n");
1990
1991 for (int i = 1; i < argc; ++i) {
1992 // Run test for each argument whose value is the exception
1993 // type to throw.
1994 runExceptionThrow(executionEngine,
1995 toRun,
1996 (unsigned) strtoul(argv[i], NULL, 10));
1997 }
1998
1999 fprintf(stderr, "\nEnd Test:\n\n");
2000 }
2001
2002 delete executionEngine;
2003
2004 return 0;
Garrison Venna2c2f1a2010-02-09 23:22:43 +00002005}
2006