blob: d94a6daab5c5d071ab084c7759b1ec0140d65e30 [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 Venn85500712011-09-22 15:45:14 +000065#ifdef OLD_EXC_SYSTEM
66// See use of UpgradeExceptionHandling(...) below
Garrison Vennaae66fa2011-09-22 14:07:50 +000067#include "llvm/AutoUpgrade.h"
Garrison Venn85500712011-09-22 15:45:14 +000068#endif
Garrison Vennaae66fa2011-09-22 14:07:50 +000069
Garrison Venn18bba842011-04-12 12:30:10 +000070// FIXME: Although all systems tested with (Linux, OS X), do not need this
71// header file included. A user on ubuntu reported, undefined symbols
72// for stderr, and fprintf, and the addition of this include fixed the
73// issue for them. Given that LLVM's best practices include the goal
74// of reducing the number of redundant header files included, the
75// correct solution would be to find out why these symbols are not
76// defined for the system in question, and fix the issue by finding out
77// which LLVM header file, if any, would include these symbols.
Garrison Venn2a7d4ad2011-04-11 19:52:49 +000078#include <cstdio>
Garrison Venn18bba842011-04-12 12:30:10 +000079
Garrison Venna2c2f1a2010-02-09 23:22:43 +000080#include <sstream>
Garrison Venna2c2f1a2010-02-09 23:22:43 +000081#include <stdexcept>
82
83
84#ifndef USE_GLOBAL_STR_CONSTS
85#define USE_GLOBAL_STR_CONSTS true
86#endif
87
88// System C++ ABI unwind types from:
89// http://refspecs.freestandards.org/abi-eh-1.21.html
90
91extern "C" {
Chris Lattner626ab1c2011-04-08 18:02:51 +000092
93 typedef enum {
Garrison Venna2c2f1a2010-02-09 23:22:43 +000094 _URC_NO_REASON = 0,
95 _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
96 _URC_FATAL_PHASE2_ERROR = 2,
97 _URC_FATAL_PHASE1_ERROR = 3,
98 _URC_NORMAL_STOP = 4,
99 _URC_END_OF_STACK = 5,
100 _URC_HANDLER_FOUND = 6,
101 _URC_INSTALL_CONTEXT = 7,
102 _URC_CONTINUE_UNWIND = 8
Chris Lattner626ab1c2011-04-08 18:02:51 +0000103 } _Unwind_Reason_Code;
104
105 typedef enum {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000106 _UA_SEARCH_PHASE = 1,
107 _UA_CLEANUP_PHASE = 2,
108 _UA_HANDLER_FRAME = 4,
109 _UA_FORCE_UNWIND = 8,
110 _UA_END_OF_STACK = 16
Chris Lattner626ab1c2011-04-08 18:02:51 +0000111 } _Unwind_Action;
112
113 struct _Unwind_Exception;
114
115 typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
116 struct _Unwind_Exception *);
117
118 struct _Unwind_Exception {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000119 uint64_t exception_class;
120 _Unwind_Exception_Cleanup_Fn exception_cleanup;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000121
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000122 uintptr_t private_1;
123 uintptr_t private_2;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000124
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000125 // @@@ The IA-64 ABI says that this structure must be double-word aligned.
126 // Taking that literally does not make much sense generically. Instead
127 // we provide the maximum alignment required by any type for the machine.
Chris Lattner626ab1c2011-04-08 18:02:51 +0000128 } __attribute__((__aligned__));
129
130 struct _Unwind_Context;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000131 typedef struct _Unwind_Context *_Unwind_Context_t;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000132
Garrison Venn64cfcef2011-04-10 14:06:52 +0000133 extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000134 extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);
135 extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);
136 extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);
137 extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);
138 extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);
139
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000140} // extern "C"
141
142//
143// Example types
144//
145
146/// This is our simplistic type info
147struct OurExceptionType_t {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000148 /// type info type
149 int type;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000150};
151
152
153/// This is our Exception class which relies on a negative offset to calculate
154/// pointers to its instances from pointers to its unwindException member.
155///
156/// Note: The above unwind.h defines struct _Unwind_Exception to be aligned
157/// on a double word boundary. This is necessary to match the standard:
158/// http://refspecs.freestandards.org/abi-eh-1.21.html
159struct OurBaseException_t {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000160 struct OurExceptionType_t type;
161
162 // Note: This is properly aligned in unwind.h
163 struct _Unwind_Exception unwindException;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000164};
165
166
167// Note: Not needed since we are C++
168typedef struct OurBaseException_t OurException;
169typedef struct _Unwind_Exception OurUnwindException;
170
171//
172// Various globals used to support typeinfo and generatted exceptions in
173// general
174//
175
176static std::map<std::string, llvm::Value*> namedValues;
177
178int64_t ourBaseFromUnwindOffset;
179
180const unsigned char ourBaseExcpClassChars[] =
Chris Lattner626ab1c2011-04-08 18:02:51 +0000181{'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000182
183
184static uint64_t ourBaseExceptionClass = 0;
185
186static std::vector<std::string> ourTypeInfoNames;
187static std::map<int, std::string> ourTypeInfoNamesIndex;
188
Garrison Venn64cfcef2011-04-10 14:06:52 +0000189static llvm::StructType *ourTypeInfoType;
Garrison Venn85500712011-09-22 15:45:14 +0000190#ifndef OLD_EXC_SYSTEM
191static llvm::StructType *ourCaughtResultType;
192#endif
Garrison Venn64cfcef2011-04-10 14:06:52 +0000193static llvm::StructType *ourExceptionType;
194static llvm::StructType *ourUnwindExceptionType;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000195
Garrison Venn64cfcef2011-04-10 14:06:52 +0000196static llvm::ConstantInt *ourExceptionNotThrownState;
197static llvm::ConstantInt *ourExceptionThrownState;
198static llvm::ConstantInt *ourExceptionCaughtState;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000199
200typedef std::vector<std::string> ArgNames;
Garrison Venn6e6cdd02011-07-11 16:31:53 +0000201typedef std::vector<llvm::Type*> ArgTypes;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000202
203//
204// Code Generation Utilities
205//
206
207/// Utility used to create a function, both declarations and definitions
208/// @param module for module instance
209/// @param retType function return type
210/// @param theArgTypes function's ordered argument types
211/// @param theArgNames function's ordered arguments needed if use of this
212/// function corresponds to a function definition. Use empty
213/// aggregate for function declarations.
214/// @param functName function name
215/// @param linkage function linkage
216/// @param declarationOnly for function declarations
217/// @param isVarArg function uses vararg arguments
218/// @returns function instance
Garrison Venn64cfcef2011-04-10 14:06:52 +0000219llvm::Function *createFunction(llvm::Module &module,
Chris Lattner77613d42011-07-18 04:52:09 +0000220 llvm::Type *retType,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000221 const ArgTypes &theArgTypes,
222 const ArgNames &theArgNames,
223 const std::string &functName,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000224 llvm::GlobalValue::LinkageTypes linkage,
225 bool declarationOnly,
226 bool isVarArg) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000227 llvm::FunctionType *functType =
228 llvm::FunctionType::get(retType, theArgTypes, isVarArg);
229 llvm::Function *ret =
230 llvm::Function::Create(functType, linkage, functName, &module);
231 if (!ret || declarationOnly)
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000232 return(ret);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000233
234 namedValues.clear();
235 unsigned i = 0;
236 for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
237 i != theArgNames.size();
238 ++argIndex, ++i) {
239
240 argIndex->setName(theArgNames[i]);
241 namedValues[theArgNames[i]] = argIndex;
242 }
243
244 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000245}
246
247
248/// Create an alloca instruction in the entry block of
249/// the parent function. This is used for mutable variables etc.
250/// @param function parent instance
251/// @param varName stack variable name
252/// @param type stack variable type
253/// @param initWith optional constant initialization value
254/// @returns AllocaInst instance
Garrison Venn64cfcef2011-04-10 14:06:52 +0000255static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000256 const std::string &varName,
Chris Lattner77613d42011-07-18 04:52:09 +0000257 llvm::Type *type,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000258 llvm::Constant *initWith = 0) {
259 llvm::BasicBlock &block = function.getEntryBlock();
Chris Lattner626ab1c2011-04-08 18:02:51 +0000260 llvm::IRBuilder<> tmp(&block, block.begin());
Garrison Venn64cfcef2011-04-10 14:06:52 +0000261 llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());
Chris Lattner626ab1c2011-04-08 18:02:51 +0000262
263 if (initWith)
264 tmp.CreateStore(initWith, ret);
265
266 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000267}
268
269
270//
271// Code Generation Utilities End
272//
273
274//
275// Runtime C Library functions
276//
277
278// Note: using an extern "C" block so that static functions can be used
279extern "C" {
280
281// Note: Better ways to decide on bit width
282//
283/// Prints a 32 bit number, according to the format, to stderr.
284/// @param intToPrint integer to print
285/// @param format printf like format to use when printing
Garrison Venn64cfcef2011-04-10 14:06:52 +0000286void print32Int(int intToPrint, const char *format) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000287 if (format) {
288 // Note: No NULL check
289 fprintf(stderr, format, intToPrint);
290 }
291 else {
292 // Note: No NULL check
293 fprintf(stderr, "::print32Int(...):NULL arg.\n");
294 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000295}
296
297
298// Note: Better ways to decide on bit width
299//
300/// Prints a 64 bit number, according to the format, to stderr.
301/// @param intToPrint integer to print
302/// @param format printf like format to use when printing
Garrison Venn64cfcef2011-04-10 14:06:52 +0000303void print64Int(long int intToPrint, const char *format) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000304 if (format) {
305 // Note: No NULL check
306 fprintf(stderr, format, intToPrint);
307 }
308 else {
309 // Note: No NULL check
310 fprintf(stderr, "::print64Int(...):NULL arg.\n");
311 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000312}
313
314
315/// Prints a C string to stderr
316/// @param toPrint string to print
Garrison Venn64cfcef2011-04-10 14:06:52 +0000317void printStr(char *toPrint) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000318 if (toPrint) {
319 fprintf(stderr, "%s", toPrint);
320 }
321 else {
322 fprintf(stderr, "::printStr(...):NULL arg.\n");
323 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000324}
325
326
327/// Deletes the true previosly allocated exception whose address
328/// is calculated from the supplied OurBaseException_t::unwindException
329/// member address. Handles (ignores), NULL pointers.
330/// @param expToDelete exception to delete
Garrison Venn64cfcef2011-04-10 14:06:52 +0000331void deleteOurException(OurUnwindException *expToDelete) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000332#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000333 fprintf(stderr,
334 "deleteOurException(...).\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000335#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000336
337 if (expToDelete &&
338 (expToDelete->exception_class == ourBaseExceptionClass)) {
339
340 free(((char*) expToDelete) + ourBaseFromUnwindOffset);
341 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000342}
343
344
345/// This function is the struct _Unwind_Exception API mandated delete function
346/// used by foreign exception handlers when deleting our exception
347/// (OurException), instances.
348/// @param reason @link http://refspecs.freestandards.org/abi-eh-1.21.html
349/// @unlink
350/// @param expToDelete exception instance to delete
351void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000352 OurUnwindException *expToDelete) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000353#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000354 fprintf(stderr,
355 "deleteFromUnwindOurException(...).\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000356#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000357
358 deleteOurException(expToDelete);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000359}
360
361
362/// Creates (allocates on the heap), an exception (OurException instance),
363/// of the supplied type info type.
364/// @param type type info type
Garrison Venn64cfcef2011-04-10 14:06:52 +0000365OurUnwindException *createOurException(int type) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000366 size_t size = sizeof(OurException);
Garrison Venn64cfcef2011-04-10 14:06:52 +0000367 OurException *ret = (OurException*) memset(malloc(size), 0, size);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000368 (ret->type).type = type;
369 (ret->unwindException).exception_class = ourBaseExceptionClass;
370 (ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
371
372 return(&(ret->unwindException));
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000373}
374
375
376/// Read a uleb128 encoded value and advance pointer
377/// See Variable Length Data in:
378/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
379/// @param data reference variable holding memory pointer to decode from
380/// @returns decoded value
Garrison Venn64cfcef2011-04-10 14:06:52 +0000381static uintptr_t readULEB128(const uint8_t **data) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000382 uintptr_t result = 0;
383 uintptr_t shift = 0;
384 unsigned char byte;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000385 const uint8_t *p = *data;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000386
387 do {
388 byte = *p++;
389 result |= (byte & 0x7f) << shift;
390 shift += 7;
391 }
392 while (byte & 0x80);
393
394 *data = p;
395
396 return result;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000397}
398
399
400/// Read a sleb128 encoded value and advance pointer
401/// See Variable Length Data in:
402/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
403/// @param data reference variable holding memory pointer to decode from
404/// @returns decoded value
Garrison Venn64cfcef2011-04-10 14:06:52 +0000405static uintptr_t readSLEB128(const uint8_t **data) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000406 uintptr_t result = 0;
407 uintptr_t shift = 0;
408 unsigned char byte;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000409 const uint8_t *p = *data;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000410
411 do {
412 byte = *p++;
413 result |= (byte & 0x7f) << shift;
414 shift += 7;
415 }
416 while (byte & 0x80);
417
418 *data = p;
419
420 if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
421 result |= (~0 << shift);
422 }
423
424 return result;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000425}
426
427
428/// Read a pointer encoded value and advance pointer
429/// See Variable Length Data in:
430/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
431/// @param data reference variable holding memory pointer to decode from
432/// @param encoding dwarf encoding type
433/// @returns decoded value
Garrison Venn64cfcef2011-04-10 14:06:52 +0000434static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000435 uintptr_t result = 0;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000436 const uint8_t *p = *data;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000437
438 if (encoding == llvm::dwarf::DW_EH_PE_omit)
439 return(result);
440
441 // first get value
442 switch (encoding & 0x0F) {
443 case llvm::dwarf::DW_EH_PE_absptr:
444 result = *((uintptr_t*)p);
445 p += sizeof(uintptr_t);
446 break;
447 case llvm::dwarf::DW_EH_PE_uleb128:
448 result = readULEB128(&p);
449 break;
450 // Note: This case has not been tested
451 case llvm::dwarf::DW_EH_PE_sleb128:
452 result = readSLEB128(&p);
453 break;
454 case llvm::dwarf::DW_EH_PE_udata2:
455 result = *((uint16_t*)p);
456 p += sizeof(uint16_t);
457 break;
458 case llvm::dwarf::DW_EH_PE_udata4:
459 result = *((uint32_t*)p);
460 p += sizeof(uint32_t);
461 break;
462 case llvm::dwarf::DW_EH_PE_udata8:
463 result = *((uint64_t*)p);
464 p += sizeof(uint64_t);
465 break;
466 case llvm::dwarf::DW_EH_PE_sdata2:
467 result = *((int16_t*)p);
468 p += sizeof(int16_t);
469 break;
470 case llvm::dwarf::DW_EH_PE_sdata4:
471 result = *((int32_t*)p);
472 p += sizeof(int32_t);
473 break;
474 case llvm::dwarf::DW_EH_PE_sdata8:
475 result = *((int64_t*)p);
476 p += sizeof(int64_t);
477 break;
478 default:
479 // not supported
480 abort();
481 break;
482 }
483
484 // then add relative offset
485 switch (encoding & 0x70) {
486 case llvm::dwarf::DW_EH_PE_absptr:
487 // do nothing
488 break;
489 case llvm::dwarf::DW_EH_PE_pcrel:
490 result += (uintptr_t)(*data);
491 break;
492 case llvm::dwarf::DW_EH_PE_textrel:
493 case llvm::dwarf::DW_EH_PE_datarel:
494 case llvm::dwarf::DW_EH_PE_funcrel:
495 case llvm::dwarf::DW_EH_PE_aligned:
496 default:
497 // not supported
498 abort();
499 break;
500 }
501
502 // then apply indirection
503 if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
504 result = *((uintptr_t*)result);
505 }
506
507 *data = p;
508
509 return result;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000510}
511
512
513/// Deals with Dwarf actions matching our type infos
514/// (OurExceptionType_t instances). Returns whether or not a dwarf emitted
515/// action matches the supplied exception type. If such a match succeeds,
516/// the resultAction argument will be set with > 0 index value. Only
517/// corresponding llvm.eh.selector type info arguments, cleanup arguments
518/// are supported. Filters are not supported.
519/// See Variable Length Data in:
520/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
521/// Also see @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
522/// @param resultAction reference variable which will be set with result
523/// @param classInfo our array of type info pointers (to globals)
524/// @param actionEntry index into above type info array or 0 (clean up).
525/// We do not support filters.
526/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
527/// of thrown exception.
528/// @param exceptionObject thrown _Unwind_Exception instance.
529/// @returns whether or not a type info was found. False is returned if only
530/// a cleanup was found
531static bool handleActionValue(int64_t *resultAction,
532 struct OurExceptionType_t **classInfo,
533 uintptr_t actionEntry,
534 uint64_t exceptionClass,
535 struct _Unwind_Exception *exceptionObject) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000536 bool ret = false;
537
538 if (!resultAction ||
539 !exceptionObject ||
540 (exceptionClass != ourBaseExceptionClass))
541 return(ret);
542
Garrison Venn64cfcef2011-04-10 14:06:52 +0000543 struct OurBaseException_t *excp = (struct OurBaseException_t*)
Chris Lattner626ab1c2011-04-08 18:02:51 +0000544 (((char*) exceptionObject) + ourBaseFromUnwindOffset);
545 struct OurExceptionType_t *excpType = &(excp->type);
546 int type = excpType->type;
547
548#ifdef DEBUG
549 fprintf(stderr,
550 "handleActionValue(...): exceptionObject = <%p>, "
551 "excp = <%p>.\n",
552 exceptionObject,
553 excp);
554#endif
555
556 const uint8_t *actionPos = (uint8_t*) actionEntry,
557 *tempActionPos;
558 int64_t typeOffset = 0,
559 actionOffset;
560
561 for (int i = 0; true; ++i) {
562 // Each emitted dwarf action corresponds to a 2 tuple of
563 // type info address offset, and action offset to the next
564 // emitted action.
565 typeOffset = readSLEB128(&actionPos);
566 tempActionPos = actionPos;
567 actionOffset = readSLEB128(&tempActionPos);
568
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000569#ifdef DEBUG
570 fprintf(stderr,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000571 "handleActionValue(...):typeOffset: <%lld>, "
572 "actionOffset: <%lld>.\n",
573 typeOffset,
574 actionOffset);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000575#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000576 assert((typeOffset >= 0) &&
577 "handleActionValue(...):filters are not supported.");
578
579 // Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
580 // argument has been matched.
581 if ((typeOffset > 0) &&
582 (type == (classInfo[-typeOffset])->type)) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000583#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000584 fprintf(stderr,
585 "handleActionValue(...):actionValue <%d> found.\n",
586 i);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000587#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000588 *resultAction = i + 1;
589 ret = true;
590 break;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000591 }
Chris Lattner626ab1c2011-04-08 18:02:51 +0000592
593#ifdef DEBUG
594 fprintf(stderr,
595 "handleActionValue(...):actionValue not found.\n");
596#endif
597 if (!actionOffset)
598 break;
599
600 actionPos += actionOffset;
601 }
602
603 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000604}
605
606
607/// Deals with the Language specific data portion of the emitted dwarf code.
608/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
609/// @param version unsupported (ignored), unwind version
610/// @param lsda language specific data area
611/// @param _Unwind_Action actions minimally supported unwind stage
612/// (forced specifically not supported)
613/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
614/// of thrown exception.
615/// @param exceptionObject thrown _Unwind_Exception instance.
616/// @param context unwind system context
617/// @returns minimally supported unwinding control indicator
618static _Unwind_Reason_Code handleLsda(int version,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000619 const uint8_t *lsda,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000620 _Unwind_Action actions,
621 uint64_t exceptionClass,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000622 struct _Unwind_Exception *exceptionObject,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000623 _Unwind_Context_t context) {
624 _Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
625
626 if (!lsda)
627 return(ret);
628
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000629#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000630 fprintf(stderr,
631 "handleLsda(...):lsda is non-zero.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000632#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000633
634 // Get the current instruction pointer and offset it before next
635 // instruction in the current frame which threw the exception.
636 uintptr_t pc = _Unwind_GetIP(context)-1;
637
638 // Get beginning current frame's code (as defined by the
639 // emitted dwarf code)
640 uintptr_t funcStart = _Unwind_GetRegionStart(context);
641 uintptr_t pcOffset = pc - funcStart;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000642 struct OurExceptionType_t **classInfo = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000643
644 // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
645 // dwarf emission
646
647 // Parse LSDA header.
648 uint8_t lpStartEncoding = *lsda++;
649
650 if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
651 readEncodedPointer(&lsda, lpStartEncoding);
652 }
653
654 uint8_t ttypeEncoding = *lsda++;
655 uintptr_t classInfoOffset;
656
657 if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
658 // Calculate type info locations in emitted dwarf code which
659 // were flagged by type info arguments to llvm.eh.selector
660 // intrinsic
661 classInfoOffset = readULEB128(&lsda);
662 classInfo = (struct OurExceptionType_t**) (lsda + classInfoOffset);
663 }
664
665 // Walk call-site table looking for range that
666 // includes current PC.
667
668 uint8_t callSiteEncoding = *lsda++;
669 uint32_t callSiteTableLength = readULEB128(&lsda);
Garrison Venn64cfcef2011-04-10 14:06:52 +0000670 const uint8_t *callSiteTableStart = lsda;
671 const uint8_t *callSiteTableEnd = callSiteTableStart +
Chris Lattner626ab1c2011-04-08 18:02:51 +0000672 callSiteTableLength;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000673 const uint8_t *actionTableStart = callSiteTableEnd;
674 const uint8_t *callSitePtr = callSiteTableStart;
Chris Lattner626ab1c2011-04-08 18:02:51 +0000675
676 bool foreignException = false;
677
678 while (callSitePtr < callSiteTableEnd) {
679 uintptr_t start = readEncodedPointer(&callSitePtr,
680 callSiteEncoding);
681 uintptr_t length = readEncodedPointer(&callSitePtr,
682 callSiteEncoding);
683 uintptr_t landingPad = readEncodedPointer(&callSitePtr,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000684 callSiteEncoding);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000685
686 // Note: Action value
687 uintptr_t actionEntry = readULEB128(&callSitePtr);
688
689 if (exceptionClass != ourBaseExceptionClass) {
690 // We have been notified of a foreign exception being thrown,
691 // and we therefore need to execute cleanup landing pads
692 actionEntry = 0;
693 foreignException = true;
694 }
695
696 if (landingPad == 0) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000697#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000698 fprintf(stderr,
699 "handleLsda(...): No landing pad found.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000700#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000701
702 continue; // no landing pad for this entry
703 }
704
705 if (actionEntry) {
706 actionEntry += ((uintptr_t) actionTableStart) - 1;
707 }
708 else {
709#ifdef DEBUG
710 fprintf(stderr,
711 "handleLsda(...):No action table found.\n");
712#endif
713 }
714
715 bool exceptionMatched = false;
716
717 if ((start <= pcOffset) && (pcOffset < (start + length))) {
718#ifdef DEBUG
719 fprintf(stderr,
720 "handleLsda(...): Landing pad found.\n");
721#endif
722 int64_t actionValue = 0;
723
724 if (actionEntry) {
Garrison Venn64cfcef2011-04-10 14:06:52 +0000725 exceptionMatched = handleActionValue(&actionValue,
726 classInfo,
727 actionEntry,
728 exceptionClass,
729 exceptionObject);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000730 }
731
732 if (!(actions & _UA_SEARCH_PHASE)) {
733#ifdef DEBUG
734 fprintf(stderr,
735 "handleLsda(...): installed landing pad "
736 "context.\n");
737#endif
738
739 // Found landing pad for the PC.
740 // Set Instruction Pointer to so we re-enter function
741 // at landing pad. The landing pad is created by the
742 // compiler to take two parameters in registers.
743 _Unwind_SetGR(context,
744 __builtin_eh_return_data_regno(0),
745 (uintptr_t)exceptionObject);
746
747 // Note: this virtual register directly corresponds
748 // to the return of the llvm.eh.selector intrinsic
749 if (!actionEntry || !exceptionMatched) {
750 // We indicate cleanup only
751 _Unwind_SetGR(context,
752 __builtin_eh_return_data_regno(1),
753 0);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000754 }
755 else {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000756 // Matched type info index of llvm.eh.selector intrinsic
757 // passed here.
758 _Unwind_SetGR(context,
759 __builtin_eh_return_data_regno(1),
760 actionValue);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000761 }
Chris Lattner626ab1c2011-04-08 18:02:51 +0000762
763 // To execute landing pad set here
764 _Unwind_SetIP(context, funcStart + landingPad);
765 ret = _URC_INSTALL_CONTEXT;
766 }
767 else if (exceptionMatched) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000768#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000769 fprintf(stderr,
770 "handleLsda(...): setting handler found.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000771#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000772 ret = _URC_HANDLER_FOUND;
773 }
774 else {
775 // Note: Only non-clean up handlers are marked as
776 // found. Otherwise the clean up handlers will be
777 // re-found and executed during the clean up
778 // phase.
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000779#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000780 fprintf(stderr,
781 "handleLsda(...): cleanup handler found.\n");
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000782#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000783 }
784
785 break;
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000786 }
Chris Lattner626ab1c2011-04-08 18:02:51 +0000787 }
788
789 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000790}
791
792
793/// This is the personality function which is embedded (dwarf emitted), in the
794/// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
795/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
796/// @param version unsupported (ignored), unwind version
797/// @param _Unwind_Action actions minimally supported unwind stage
798/// (forced specifically not supported)
799/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
800/// of thrown exception.
801/// @param exceptionObject thrown _Unwind_Exception instance.
802/// @param context unwind system context
803/// @returns minimally supported unwinding control indicator
804_Unwind_Reason_Code ourPersonality(int version,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000805 _Unwind_Action actions,
806 uint64_t exceptionClass,
Garrison Venn64cfcef2011-04-10 14:06:52 +0000807 struct _Unwind_Exception *exceptionObject,
Chris Lattner626ab1c2011-04-08 18:02:51 +0000808 _Unwind_Context_t context) {
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000809#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000810 fprintf(stderr,
811 "We are in ourPersonality(...):actions is <%d>.\n",
812 actions);
813
814 if (actions & _UA_SEARCH_PHASE) {
815 fprintf(stderr, "ourPersonality(...):In search phase.\n");
816 }
817 else {
818 fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
819 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000820#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000821
Garrison Venn64cfcef2011-04-10 14:06:52 +0000822 const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
Chris Lattner626ab1c2011-04-08 18:02:51 +0000823
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000824#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +0000825 fprintf(stderr,
826 "ourPersonality(...):lsda = <%p>.\n",
827 lsda);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000828#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +0000829
830 // The real work of the personality function is captured here
831 return(handleLsda(version,
832 lsda,
833 actions,
834 exceptionClass,
835 exceptionObject,
836 context));
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000837}
838
839
840/// Generates our _Unwind_Exception class from a given character array.
841/// thereby handling arbitrary lengths (not in standard), and handling
842/// embedded \0s.
843/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
844/// @param classChars char array to encode. NULL values not checkedf
845/// @param classCharsSize number of chars in classChars. Value is not checked.
846/// @returns class value
847uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
848{
Chris Lattner626ab1c2011-04-08 18:02:51 +0000849 uint64_t ret = classChars[0];
850
851 for (unsigned i = 1; i < classCharsSize; ++i) {
852 ret <<= 8;
853 ret += classChars[i];
854 }
855
856 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000857}
858
859} // extern "C"
860
861//
862// Runtime C Library functions End
863//
864
865//
866// Code generation functions
867//
868
869/// Generates code to print given constant string
870/// @param context llvm context
871/// @param module code for module instance
872/// @param builder builder instance
873/// @param toPrint string to print
874/// @param useGlobal A value of true (default) indicates a GlobalValue is
875/// generated, and is used to hold the constant string. A value of
876/// false indicates that the constant string will be stored on the
877/// stack.
Garrison Venn64cfcef2011-04-10 14:06:52 +0000878void generateStringPrint(llvm::LLVMContext &context,
879 llvm::Module &module,
880 llvm::IRBuilder<> &builder,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000881 std::string toPrint,
882 bool useGlobal = true) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000883 llvm::Function *printFunct = module.getFunction("printStr");
884
885 llvm::Value *stringVar;
Garrison Venn64cfcef2011-04-10 14:06:52 +0000886 llvm::Constant *stringConstant =
Chris Lattner626ab1c2011-04-08 18:02:51 +0000887 llvm::ConstantArray::get(context, toPrint);
888
889 if (useGlobal) {
890 // Note: Does not work without allocation
891 stringVar =
892 new llvm::GlobalVariable(module,
893 stringConstant->getType(),
894 true,
895 llvm::GlobalValue::LinkerPrivateLinkage,
896 stringConstant,
897 "");
898 }
899 else {
900 stringVar = builder.CreateAlloca(stringConstant->getType());
901 builder.CreateStore(stringConstant, stringVar);
902 }
903
Garrison Venn64cfcef2011-04-10 14:06:52 +0000904 llvm::Value *cast =
Chris Lattner626ab1c2011-04-08 18:02:51 +0000905 builder.CreatePointerCast(stringVar,
Garrison Vennc0f33cb2011-07-12 15:34:42 +0000906 builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +0000907 builder.CreateCall(printFunct, cast);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000908}
909
910
911/// Generates code to print given runtime integer according to constant
912/// string format, and a given print function.
913/// @param context llvm context
914/// @param module code for module instance
915/// @param builder builder instance
916/// @param printFunct function used to "print" integer
917/// @param toPrint string to print
918/// @param format printf like formating string for print
919/// @param useGlobal A value of true (default) indicates a GlobalValue is
920/// generated, and is used to hold the constant string. A value of
921/// false indicates that the constant string will be stored on the
922/// stack.
Garrison Venn64cfcef2011-04-10 14:06:52 +0000923void generateIntegerPrint(llvm::LLVMContext &context,
924 llvm::Module &module,
925 llvm::IRBuilder<> &builder,
926 llvm::Function &printFunct,
927 llvm::Value &toPrint,
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000928 std::string format,
929 bool useGlobal = true) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000930 llvm::Constant *stringConstant = llvm::ConstantArray::get(context, format);
931 llvm::Value *stringVar;
932
933 if (useGlobal) {
934 // Note: Does not seem to work without allocation
935 stringVar =
936 new llvm::GlobalVariable(module,
937 stringConstant->getType(),
938 true,
939 llvm::GlobalValue::LinkerPrivateLinkage,
940 stringConstant,
941 "");
942 }
943 else {
944 stringVar = builder.CreateAlloca(stringConstant->getType());
945 builder.CreateStore(stringConstant, stringVar);
946 }
947
Garrison Venn64cfcef2011-04-10 14:06:52 +0000948 llvm::Value *cast =
Chris Lattner626ab1c2011-04-08 18:02:51 +0000949 builder.CreateBitCast(stringVar,
Garrison Vennc0f33cb2011-07-12 15:34:42 +0000950 builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +0000951 builder.CreateCall2(&printFunct, &toPrint, cast);
Garrison Venna2c2f1a2010-02-09 23:22:43 +0000952}
953
954
955/// Generates code to handle finally block type semantics: always runs
956/// regardless of whether a thrown exception is passing through or the
957/// parent function is simply exiting. In addition to printing some state
958/// to stderr, this code will resume the exception handling--runs the
959/// unwind resume block, if the exception has not been previously caught
960/// by a catch clause, and will otherwise execute the end block (terminator
961/// block). In addition this function creates the corresponding function's
962/// stack storage for the exception pointer and catch flag status.
963/// @param context llvm context
964/// @param module code for module instance
965/// @param builder builder instance
966/// @param toAddTo parent function to add block to
967/// @param blockName block name of new "finally" block.
968/// @param functionId output id used for printing
969/// @param terminatorBlock terminator "end" block
970/// @param unwindResumeBlock unwind resume block
971/// @param exceptionCaughtFlag reference exception caught/thrown status storage
972/// @param exceptionStorage reference to exception pointer storage
973/// @returns newly created block
Garrison Venn64cfcef2011-04-10 14:06:52 +0000974static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context,
975 llvm::Module &module,
976 llvm::IRBuilder<> &builder,
977 llvm::Function &toAddTo,
978 std::string &blockName,
979 std::string &functionId,
980 llvm::BasicBlock &terminatorBlock,
981 llvm::BasicBlock &unwindResumeBlock,
982 llvm::Value **exceptionCaughtFlag,
983 llvm::Value **exceptionStorage) {
Chris Lattner626ab1c2011-04-08 18:02:51 +0000984 assert(exceptionCaughtFlag &&
985 "ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
986 "is NULL");
987 assert(exceptionStorage &&
988 "ExceptionDemo::createFinallyBlock(...):exceptionStorage "
989 "is NULL");
990
991 *exceptionCaughtFlag =
992 createEntryBlockAlloca(toAddTo,
993 "exceptionCaught",
994 ourExceptionNotThrownState->getType(),
995 ourExceptionNotThrownState);
996
Chris Lattner77613d42011-07-18 04:52:09 +0000997 llvm::PointerType *exceptionStorageType = builder.getInt8PtrTy();
Chris Lattner626ab1c2011-04-08 18:02:51 +0000998 *exceptionStorage =
999 createEntryBlockAlloca(toAddTo,
1000 "exceptionStorage",
1001 exceptionStorageType,
1002 llvm::ConstantPointerNull::get(
1003 exceptionStorageType));
1004
1005 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1006 blockName,
1007 &toAddTo);
1008
1009 builder.SetInsertPoint(ret);
1010
1011 std::ostringstream bufferToPrint;
1012 bufferToPrint << "Gen: Executing finally block "
1013 << blockName << " in " << functionId << "\n";
1014 generateStringPrint(context,
1015 module,
1016 builder,
1017 bufferToPrint.str(),
1018 USE_GLOBAL_STR_CONSTS);
1019
Garrison Venn64cfcef2011-04-10 14:06:52 +00001020 llvm::SwitchInst *theSwitch =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001021 builder.CreateSwitch(builder.CreateLoad(*exceptionCaughtFlag),
1022 &terminatorBlock,
1023 2);
1024 theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
1025 theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
1026
1027 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001028}
1029
1030
1031/// Generates catch block semantics which print a string to indicate type of
1032/// catch executed, sets an exception caught flag, and executes passed in
1033/// end block (terminator block).
1034/// @param context llvm context
1035/// @param module code for module instance
1036/// @param builder builder instance
1037/// @param toAddTo parent function to add block to
1038/// @param blockName block name of new "catch" block.
1039/// @param functionId output id used for printing
1040/// @param terminatorBlock terminator "end" block
1041/// @param exceptionCaughtFlag exception caught/thrown status
1042/// @returns newly created block
Garrison Venn64cfcef2011-04-10 14:06:52 +00001043static llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context,
1044 llvm::Module &module,
1045 llvm::IRBuilder<> &builder,
1046 llvm::Function &toAddTo,
1047 std::string &blockName,
1048 std::string &functionId,
1049 llvm::BasicBlock &terminatorBlock,
1050 llvm::Value &exceptionCaughtFlag) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001051
1052 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1053 blockName,
1054 &toAddTo);
1055
1056 builder.SetInsertPoint(ret);
1057
1058 std::ostringstream bufferToPrint;
1059 bufferToPrint << "Gen: Executing catch block "
1060 << blockName
1061 << " in "
1062 << functionId
1063 << std::endl;
1064 generateStringPrint(context,
1065 module,
1066 builder,
1067 bufferToPrint.str(),
1068 USE_GLOBAL_STR_CONSTS);
1069 builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
1070 builder.CreateBr(&terminatorBlock);
1071
1072 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001073}
1074
1075
1076/// Generates a function which invokes a function (toInvoke) and, whose
1077/// unwind block will "catch" the type info types correspondingly held in the
1078/// exceptionTypesToCatch argument. If the toInvoke function throws an
1079/// exception which does not match any type info types contained in
1080/// exceptionTypesToCatch, the generated code will call _Unwind_Resume
1081/// with the raised exception. On the other hand the generated code will
1082/// normally exit if the toInvoke function does not throw an exception.
1083/// The generated "finally" block is always run regardless of the cause of
1084/// the generated function exit.
1085/// The generated function is returned after being verified.
1086/// @param module code for module instance
1087/// @param builder builder instance
1088/// @param fpm a function pass manager holding optional IR to IR
1089/// transformations
1090/// @param toInvoke inner function to invoke
1091/// @param ourId id used to printing purposes
1092/// @param numExceptionsToCatch length of exceptionTypesToCatch array
1093/// @param exceptionTypesToCatch array of type info types to "catch"
1094/// @returns generated function
1095static
Garrison Venn64cfcef2011-04-10 14:06:52 +00001096llvm::Function *createCatchWrappedInvokeFunction(llvm::Module &module,
1097 llvm::IRBuilder<> &builder,
1098 llvm::FunctionPassManager &fpm,
1099 llvm::Function &toInvoke,
1100 std::string ourId,
1101 unsigned numExceptionsToCatch,
1102 unsigned exceptionTypesToCatch[]) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001103
Garrison Venn64cfcef2011-04-10 14:06:52 +00001104 llvm::LLVMContext &context = module.getContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001105 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1106
1107 ArgTypes argTypes;
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001108 argTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001109
1110 ArgNames argNames;
1111 argNames.push_back("exceptTypeToThrow");
1112
Garrison Venn64cfcef2011-04-10 14:06:52 +00001113 llvm::Function *ret = createFunction(module,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001114 builder.getVoidTy(),
1115 argTypes,
1116 argNames,
1117 ourId,
1118 llvm::Function::ExternalLinkage,
1119 false,
1120 false);
1121
1122 // Block which calls invoke
1123 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1124 "entry",
1125 ret);
1126 // Normal block for invoke
1127 llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,
1128 "normal",
1129 ret);
1130 // Unwind block for invoke
1131 llvm::BasicBlock *exceptionBlock =
1132 llvm::BasicBlock::Create(context, "exception", ret);
1133
1134 // Block which routes exception to correct catch handler block
1135 llvm::BasicBlock *exceptionRouteBlock =
1136 llvm::BasicBlock::Create(context, "exceptionRoute", ret);
1137
1138 // Foreign exception handler
1139 llvm::BasicBlock *externalExceptionBlock =
1140 llvm::BasicBlock::Create(context, "externalException", ret);
1141
1142 // Block which calls _Unwind_Resume
1143 llvm::BasicBlock *unwindResumeBlock =
1144 llvm::BasicBlock::Create(context, "unwindResume", ret);
1145
1146 // Clean up block which delete exception if needed
1147 llvm::BasicBlock *endBlock =
1148 llvm::BasicBlock::Create(context, "end", ret);
1149
1150 std::string nextName;
1151 std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
Garrison Venn64cfcef2011-04-10 14:06:52 +00001152 llvm::Value *exceptionCaughtFlag = NULL;
1153 llvm::Value *exceptionStorage = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +00001154
1155 // Finally block which will branch to unwindResumeBlock if
1156 // exception is not caught. Initializes/allocates stack locations.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001157 llvm::BasicBlock *finallyBlock = createFinallyBlock(context,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001158 module,
1159 builder,
1160 *ret,
1161 nextName = "finally",
1162 ourId,
1163 *endBlock,
1164 *unwindResumeBlock,
1165 &exceptionCaughtFlag,
1166 &exceptionStorage);
1167
1168 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1169 nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
1170
1171 // One catch block per type info to be caught
1172 catchBlocks[i] = createCatchBlock(context,
1173 module,
1174 builder,
1175 *ret,
1176 nextName,
1177 ourId,
1178 *finallyBlock,
1179 *exceptionCaughtFlag);
1180 }
1181
1182 // Entry Block
1183
1184 builder.SetInsertPoint(entryBlock);
1185
1186 std::vector<llvm::Value*> args;
1187 args.push_back(namedValues["exceptTypeToThrow"]);
1188 builder.CreateInvoke(&toInvoke,
1189 normalBlock,
1190 exceptionBlock,
Chris Lattner77613d42011-07-18 04:52:09 +00001191 args);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001192
1193 // End Block
1194
1195 builder.SetInsertPoint(endBlock);
1196
1197 generateStringPrint(context,
1198 module,
1199 builder,
1200 "Gen: In end block: exiting in " + ourId + ".\n",
1201 USE_GLOBAL_STR_CONSTS);
1202 llvm::Function *deleteOurException =
1203 module.getFunction("deleteOurException");
1204
1205 // Note: function handles NULL exceptions
1206 builder.CreateCall(deleteOurException,
1207 builder.CreateLoad(exceptionStorage));
1208 builder.CreateRetVoid();
1209
1210 // Normal Block
1211
1212 builder.SetInsertPoint(normalBlock);
1213
1214 generateStringPrint(context,
1215 module,
1216 builder,
1217 "Gen: No exception in " + ourId + "!\n",
1218 USE_GLOBAL_STR_CONSTS);
1219
1220 // Finally block is always called
1221 builder.CreateBr(finallyBlock);
1222
1223 // Unwind Resume Block
1224
1225 builder.SetInsertPoint(unwindResumeBlock);
1226
Garrison Venn85500712011-09-22 15:45:14 +00001227 llvm::Function *resumeOurException = module.getFunction("_Unwind_Resume");
Chris Lattner626ab1c2011-04-08 18:02:51 +00001228 builder.CreateCall(resumeOurException,
1229 builder.CreateLoad(exceptionStorage));
1230 builder.CreateUnreachable();
1231
1232 // Exception Block
1233
1234 builder.SetInsertPoint(exceptionBlock);
1235
Garrison Venn85500712011-09-22 15:45:14 +00001236 llvm::Function *personality = module.getFunction("ourPersonality");
Chris Lattner626ab1c2011-04-08 18:02:51 +00001237
Garrison Venn85500712011-09-22 15:45:14 +00001238#ifndef OLD_EXC_SYSTEM
1239 llvm::LandingPadInst *caughtResult =
1240 builder.CreateLandingPad(ourCaughtResultType,
1241 personality,
1242 numExceptionsToCatch,
1243 "landingPad");
1244
1245 caughtResult->setCleanup(true);
1246
1247 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1248 // Set up type infos to be caught
1249 caughtResult->addClause(module.getGlobalVariable(
1250 ourTypeInfoNames[exceptionTypesToCatch[i]]));
1251 }
1252
1253 llvm::Value *unwindException = builder.CreateExtractValue(caughtResult, 0);
1254 llvm::Value *retTypeInfoIndex =
1255 builder.CreateExtractValue(caughtResult, 1);
1256
1257 builder.CreateStore(unwindException, exceptionStorage);
1258 builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
1259
1260#else
1261 llvm::Function *ehException = module.getFunction("llvm.eh.exception");
1262
Chris Lattner626ab1c2011-04-08 18:02:51 +00001263 // Retrieve thrown exception
Garrison Venn64cfcef2011-04-10 14:06:52 +00001264 llvm::Value *unwindException = builder.CreateCall(ehException);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001265
1266 // Store exception and flag
1267 builder.CreateStore(unwindException, exceptionStorage);
1268 builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
Garrison Venn64cfcef2011-04-10 14:06:52 +00001269 llvm::Value *functPtr =
Garrison Venn85500712011-09-22 15:45:14 +00001270 builder.CreatePointerCast(personality, builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001271
1272 args.clear();
1273 args.push_back(unwindException);
1274 args.push_back(functPtr);
1275
1276 // Note: Skipping index 0
1277 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1278 // Set up type infos to be caught
1279 args.push_back(module.getGlobalVariable(
1280 ourTypeInfoNames[exceptionTypesToCatch[i]]));
1281 }
1282
1283 args.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), 0));
1284
1285 llvm::Function *ehSelector = module.getFunction("llvm.eh.selector");
1286
1287 // Set up this exeption block as the landing pad which will handle
1288 // given type infos. See case Intrinsic::eh_selector in
1289 // SelectionDAGBuilder::visitIntrinsicCall(...) and AddCatchInfo(...)
1290 // implemented in FunctionLoweringInfo.cpp to see how the implementation
1291 // handles this call. This landing pad (this exception block), will be
1292 // called either because it nees to cleanup (call finally) or a type
1293 // info was found which matched the thrown exception.
Chris Lattner77613d42011-07-18 04:52:09 +00001294 llvm::Value *retTypeInfoIndex = builder.CreateCall(ehSelector, args);
Garrison Venn85500712011-09-22 15:45:14 +00001295#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +00001296
1297 // Retrieve exception_class member from thrown exception
1298 // (_Unwind_Exception instance). This member tells us whether or not
1299 // the exception is foreign.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001300 llvm::Value *unwindExceptionClass =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001301 builder.CreateLoad(builder.CreateStructGEP(
1302 builder.CreatePointerCast(unwindException,
1303 ourUnwindExceptionType->getPointerTo()),
1304 0));
1305
1306 // Branch to the externalExceptionBlock if the exception is foreign or
1307 // to a catch router if not. Either way the finally block will be run.
1308 builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
1309 llvm::ConstantInt::get(builder.getInt64Ty(),
1310 ourBaseExceptionClass)),
1311 exceptionRouteBlock,
1312 externalExceptionBlock);
1313
1314 // External Exception Block
1315
1316 builder.SetInsertPoint(externalExceptionBlock);
1317
1318 generateStringPrint(context,
1319 module,
1320 builder,
1321 "Gen: Foreign exception received.\n",
1322 USE_GLOBAL_STR_CONSTS);
1323
1324 // Branch to the finally block
1325 builder.CreateBr(finallyBlock);
1326
1327 // Exception Route Block
1328
1329 builder.SetInsertPoint(exceptionRouteBlock);
1330
1331 // Casts exception pointer (_Unwind_Exception instance) to parent
1332 // (OurException instance).
1333 //
1334 // Note: ourBaseFromUnwindOffset is usually negative
Garrison Venn64cfcef2011-04-10 14:06:52 +00001335 llvm::Value *typeInfoThrown =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001336 builder.CreatePointerCast(builder.CreateConstGEP1_64(unwindException,
1337 ourBaseFromUnwindOffset),
1338 ourExceptionType->getPointerTo());
1339
1340 // Retrieve thrown exception type info type
1341 //
1342 // Note: Index is not relative to pointer but instead to structure
1343 // unlike a true getelementptr (GEP) instruction
1344 typeInfoThrown = builder.CreateStructGEP(typeInfoThrown, 0);
1345
Garrison Venn64cfcef2011-04-10 14:06:52 +00001346 llvm::Value *typeInfoThrownType =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001347 builder.CreateStructGEP(typeInfoThrown, 0);
1348
1349 generateIntegerPrint(context,
1350 module,
1351 builder,
1352 *toPrint32Int,
1353 *(builder.CreateLoad(typeInfoThrownType)),
1354 "Gen: Exception type <%d> received (stack unwound) "
1355 " in " +
1356 ourId +
1357 ".\n",
1358 USE_GLOBAL_STR_CONSTS);
1359
1360 // Route to matched type info catch block or run cleanup finally block
Garrison Venn64cfcef2011-04-10 14:06:52 +00001361 llvm::SwitchInst *switchToCatchBlock =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001362 builder.CreateSwitch(retTypeInfoIndex,
1363 finallyBlock,
1364 numExceptionsToCatch);
1365
1366 unsigned nextTypeToCatch;
1367
1368 for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
1369 nextTypeToCatch = i - 1;
1370 switchToCatchBlock->addCase(llvm::ConstantInt::get(
1371 llvm::Type::getInt32Ty(context), i),
1372 catchBlocks[nextTypeToCatch]);
1373 }
Garrison Vennaae66fa2011-09-22 14:07:50 +00001374
Garrison Venn85500712011-09-22 15:45:14 +00001375#ifdef OLD_EXC_SYSTEM
1376 // Must be run before verifier
1377 UpgradeExceptionHandling(&module);
1378#endif
1379
1380
Chris Lattner626ab1c2011-04-08 18:02:51 +00001381 llvm::verifyFunction(*ret);
1382 fpm.run(*ret);
1383
1384 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001385}
1386
1387
1388/// Generates function which throws either an exception matched to a runtime
1389/// determined type info type (argument to generated function), or if this
1390/// runtime value matches nativeThrowType, throws a foreign exception by
1391/// calling nativeThrowFunct.
1392/// @param module code for module instance
1393/// @param builder builder instance
1394/// @param fpm a function pass manager holding optional IR to IR
1395/// transformations
1396/// @param ourId id used to printing purposes
1397/// @param nativeThrowType a runtime argument of this value results in
1398/// nativeThrowFunct being called to generate/throw exception.
1399/// @param nativeThrowFunct function which will throw a foreign exception
1400/// if the above nativeThrowType matches generated function's arg.
1401/// @returns generated function
1402static
Garrison Venn64cfcef2011-04-10 14:06:52 +00001403llvm::Function *createThrowExceptionFunction(llvm::Module &module,
1404 llvm::IRBuilder<> &builder,
1405 llvm::FunctionPassManager &fpm,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001406 std::string ourId,
1407 int32_t nativeThrowType,
Garrison Venn64cfcef2011-04-10 14:06:52 +00001408 llvm::Function &nativeThrowFunct) {
1409 llvm::LLVMContext &context = module.getContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001410 namedValues.clear();
1411 ArgTypes unwindArgTypes;
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001412 unwindArgTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001413 ArgNames unwindArgNames;
1414 unwindArgNames.push_back("exceptTypeToThrow");
1415
1416 llvm::Function *ret = createFunction(module,
1417 builder.getVoidTy(),
1418 unwindArgTypes,
1419 unwindArgNames,
1420 ourId,
1421 llvm::Function::ExternalLinkage,
1422 false,
1423 false);
1424
1425 // Throws either one of our exception or a native C++ exception depending
1426 // on a runtime argument value containing a type info type.
1427 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1428 "entry",
1429 ret);
1430 // Throws a foreign exception
1431 llvm::BasicBlock *nativeThrowBlock =
1432 llvm::BasicBlock::Create(context,
1433 "nativeThrow",
1434 ret);
1435 // Throws one of our Exceptions
1436 llvm::BasicBlock *generatedThrowBlock =
1437 llvm::BasicBlock::Create(context,
1438 "generatedThrow",
1439 ret);
1440 // Retrieved runtime type info type to throw
Garrison Venn64cfcef2011-04-10 14:06:52 +00001441 llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
Chris Lattner626ab1c2011-04-08 18:02:51 +00001442
1443 // nativeThrowBlock block
1444
1445 builder.SetInsertPoint(nativeThrowBlock);
1446
1447 // Throws foreign exception
1448 builder.CreateCall(&nativeThrowFunct, exceptionType);
1449 builder.CreateUnreachable();
1450
1451 // entry block
1452
1453 builder.SetInsertPoint(entryBlock);
1454
1455 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1456 generateIntegerPrint(context,
1457 module,
1458 builder,
1459 *toPrint32Int,
1460 *exceptionType,
1461 "\nGen: About to throw exception type <%d> in " +
1462 ourId +
1463 ".\n",
1464 USE_GLOBAL_STR_CONSTS);
1465
1466 // Switches on runtime type info type value to determine whether or not
1467 // a foreign exception is thrown. Defaults to throwing one of our
1468 // generated exceptions.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001469 llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
Chris Lattner626ab1c2011-04-08 18:02:51 +00001470 generatedThrowBlock,
1471 1);
1472
1473 theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),
1474 nativeThrowType),
1475 nativeThrowBlock);
1476
1477 // generatedThrow block
1478
1479 builder.SetInsertPoint(generatedThrowBlock);
1480
1481 llvm::Function *createOurException =
1482 module.getFunction("createOurException");
1483 llvm::Function *raiseOurException =
1484 module.getFunction("_Unwind_RaiseException");
1485
1486 // Creates exception to throw with runtime type info type.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001487 llvm::Value *exception =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001488 builder.CreateCall(createOurException,
1489 namedValues["exceptTypeToThrow"]);
1490
1491 // Throw generated Exception
1492 builder.CreateCall(raiseOurException, exception);
1493 builder.CreateUnreachable();
1494
1495 llvm::verifyFunction(*ret);
1496 fpm.run(*ret);
1497
1498 return(ret);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001499}
1500
1501static void createStandardUtilityFunctions(unsigned numTypeInfos,
Garrison Venn64cfcef2011-04-10 14:06:52 +00001502 llvm::Module &module,
1503 llvm::IRBuilder<> &builder);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001504
1505/// Creates test code by generating and organizing these functions into the
1506/// test case. The test case consists of an outer function setup to invoke
1507/// an inner function within an environment having multiple catch and single
1508/// finally blocks. This inner function is also setup to invoke a throw
1509/// function within an evironment similar in nature to the outer function's
1510/// catch and finally blocks. Each of these two functions catch mutually
1511/// exclusive subsets (even or odd) of the type info types configured
1512/// for this this. All generated functions have a runtime argument which
1513/// holds a type info type to throw that each function takes and passes it
1514/// to the inner one if such a inner function exists. This type info type is
1515/// looked at by the generated throw function to see whether or not it should
1516/// throw a generated exception with the same type info type, or instead call
1517/// a supplied a function which in turn will throw a foreign exception.
1518/// @param module code for module instance
1519/// @param builder builder instance
1520/// @param fpm a function pass manager holding optional IR to IR
1521/// transformations
1522/// @param nativeThrowFunctName name of external function which will throw
1523/// a foreign exception
1524/// @returns outermost generated test function.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001525llvm::Function *createUnwindExceptionTest(llvm::Module &module,
1526 llvm::IRBuilder<> &builder,
1527 llvm::FunctionPassManager &fpm,
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001528 std::string nativeThrowFunctName) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001529 // Number of type infos to generate
1530 unsigned numTypeInfos = 6;
1531
1532 // Initialze intrisics and external functions to use along with exception
1533 // and type info globals.
1534 createStandardUtilityFunctions(numTypeInfos,
1535 module,
1536 builder);
1537 llvm::Function *nativeThrowFunct =
1538 module.getFunction(nativeThrowFunctName);
1539
1540 // Create exception throw function using the value ~0 to cause
1541 // foreign exceptions to be thrown.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001542 llvm::Function *throwFunct =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001543 createThrowExceptionFunction(module,
1544 builder,
1545 fpm,
1546 "throwFunct",
1547 ~0,
1548 *nativeThrowFunct);
1549 // Inner function will catch even type infos
1550 unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
1551 size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) /
1552 sizeof(unsigned);
1553
1554 // Generate inner function.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001555 llvm::Function *innerCatchFunct =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001556 createCatchWrappedInvokeFunction(module,
1557 builder,
1558 fpm,
1559 *throwFunct,
1560 "innerCatchFunct",
1561 numExceptionTypesToCatch,
1562 innerExceptionTypesToCatch);
1563
1564 // Outer function will catch odd type infos
1565 unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
1566 numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) /
1567 sizeof(unsigned);
1568
1569 // Generate outer function
Garrison Venn64cfcef2011-04-10 14:06:52 +00001570 llvm::Function *outerCatchFunct =
Chris Lattner626ab1c2011-04-08 18:02:51 +00001571 createCatchWrappedInvokeFunction(module,
1572 builder,
1573 fpm,
1574 *innerCatchFunct,
1575 "outerCatchFunct",
1576 numExceptionTypesToCatch,
1577 outerExceptionTypesToCatch);
1578
1579 // Return outer function to run
1580 return(outerCatchFunct);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001581}
1582
1583
1584/// Represents our foreign exceptions
1585class OurCppRunException : public std::runtime_error {
1586public:
Chris Lattner626ab1c2011-04-08 18:02:51 +00001587 OurCppRunException(const std::string reason) :
1588 std::runtime_error(reason) {}
1589
Garrison Venn64cfcef2011-04-10 14:06:52 +00001590 OurCppRunException (const OurCppRunException &toCopy) :
Chris Lattner626ab1c2011-04-08 18:02:51 +00001591 std::runtime_error(toCopy) {}
1592
Garrison Venn64cfcef2011-04-10 14:06:52 +00001593 OurCppRunException &operator = (const OurCppRunException &toCopy) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001594 return(reinterpret_cast<OurCppRunException&>(
1595 std::runtime_error::operator=(toCopy)));
1596 }
1597
1598 ~OurCppRunException (void) throw () {}
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001599};
1600
1601
1602/// Throws foreign C++ exception.
1603/// @param ignoreIt unused parameter that allows function to match implied
1604/// generated function contract.
1605extern "C"
1606void throwCppException (int32_t ignoreIt) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001607 throw(OurCppRunException("thrown by throwCppException(...)"));
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001608}
1609
1610typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
1611
1612/// This is a test harness which runs test by executing generated
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001613/// function with a type info type to throw. Harness wraps the execution
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001614/// of generated function in a C++ try catch clause.
1615/// @param engine execution engine to use for executing generated function.
1616/// This demo program expects this to be a JIT instance for demo
1617/// purposes.
1618/// @param function generated test function to run
1619/// @param typeToThrow type info type of generated exception to throw, or
1620/// indicator to cause foreign exception to be thrown.
1621static
Garrison Venn64cfcef2011-04-10 14:06:52 +00001622void runExceptionThrow(llvm::ExecutionEngine *engine,
1623 llvm::Function *function,
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001624 int32_t typeToThrow) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001625
1626 // Find test's function pointer
1627 OurExceptionThrowFunctType functPtr =
1628 reinterpret_cast<OurExceptionThrowFunctType>(
1629 reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
1630
1631 try {
1632 // Run test
1633 (*functPtr)(typeToThrow);
1634 }
1635 catch (OurCppRunException exc) {
1636 // Catch foreign C++ exception
1637 fprintf(stderr,
1638 "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
1639 "with reason: %s.\n",
1640 exc.what());
1641 }
1642 catch (...) {
1643 // Catch all exceptions including our generated ones. I'm not sure
1644 // why this latter functionality should work, as it seems that
1645 // our exceptions should be foreign to C++ (the _Unwind_Exception::
1646 // exception_class should be different from the one used by C++), and
1647 // therefore C++ should ignore the generated exceptions.
1648
1649 fprintf(stderr,
1650 "\nrunExceptionThrow(...):In C++ catch all.\n");
1651 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001652}
1653
1654//
1655// End test functions
1656//
1657
Garrison Venn6e6cdd02011-07-11 16:31:53 +00001658typedef llvm::ArrayRef<llvm::Type*> TypeArray;
Chris Lattnercad3f772011-04-08 17:56:47 +00001659
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001660/// This initialization routine creates type info globals and
1661/// adds external function declarations to module.
1662/// @param numTypeInfos number of linear type info associated type info types
1663/// to create as GlobalVariable instances, starting with the value 1.
1664/// @param module code for module instance
1665/// @param builder builder instance
1666static void createStandardUtilityFunctions(unsigned numTypeInfos,
Garrison Venn64cfcef2011-04-10 14:06:52 +00001667 llvm::Module &module,
1668 llvm::IRBuilder<> &builder) {
Chris Lattnercad3f772011-04-08 17:56:47 +00001669
Garrison Venn64cfcef2011-04-10 14:06:52 +00001670 llvm::LLVMContext &context = module.getContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001671
1672 // Exception initializations
1673
1674 // Setup exception catch state
1675 ourExceptionNotThrownState =
1676 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
1677 ourExceptionThrownState =
1678 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
1679 ourExceptionCaughtState =
1680 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
1681
1682
1683
1684 // Create our type info type
1685 ourTypeInfoType = llvm::StructType::get(context,
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001686 TypeArray(builder.getInt32Ty()));
Garrison Venn85500712011-09-22 15:45:14 +00001687
1688#ifndef OLD_EXC_SYSTEM
1689
1690 llvm::Type *caughtResultFieldTypes[] = {
1691 builder.getInt8PtrTy(),
1692 builder.getInt32Ty()
1693 };
1694
1695 // Create our landingpad result type
1696 ourCaughtResultType = llvm::StructType::get(context,
1697 TypeArray(caughtResultFieldTypes));
1698
1699#endif
1700
Chris Lattner626ab1c2011-04-08 18:02:51 +00001701 // Create OurException type
1702 ourExceptionType = llvm::StructType::get(context,
1703 TypeArray(ourTypeInfoType));
1704
1705 // Create portion of _Unwind_Exception type
1706 //
1707 // Note: Declaring only a portion of the _Unwind_Exception struct.
1708 // Does this cause problems?
1709 ourUnwindExceptionType =
Garrison Venn6e6cdd02011-07-11 16:31:53 +00001710 llvm::StructType::get(context,
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001711 TypeArray(builder.getInt64Ty()));
Garrison Venn6e6cdd02011-07-11 16:31:53 +00001712
Chris Lattner626ab1c2011-04-08 18:02:51 +00001713 struct OurBaseException_t dummyException;
1714
1715 // Calculate offset of OurException::unwindException member.
1716 ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -
Garrison Venn85500712011-09-22 15:45:14 +00001717 ((uintptr_t) &(dummyException.unwindException));
Chris Lattner626ab1c2011-04-08 18:02:51 +00001718
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001719#ifdef DEBUG
Chris Lattner626ab1c2011-04-08 18:02:51 +00001720 fprintf(stderr,
1721 "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
1722 "= %lld, sizeof(struct OurBaseException_t) - "
1723 "sizeof(struct _Unwind_Exception) = %lu.\n",
1724 ourBaseFromUnwindOffset,
1725 sizeof(struct OurBaseException_t) -
1726 sizeof(struct _Unwind_Exception));
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001727#endif
Chris Lattner626ab1c2011-04-08 18:02:51 +00001728
1729 size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
1730
1731 // Create our _Unwind_Exception::exception_class value
1732 ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
1733
1734 // Type infos
1735
1736 std::string baseStr = "typeInfo", typeInfoName;
1737 std::ostringstream typeInfoNameBuilder;
1738 std::vector<llvm::Constant*> structVals;
1739
1740 llvm::Constant *nextStruct;
Garrison Venn64cfcef2011-04-10 14:06:52 +00001741 llvm::GlobalVariable *nextGlobal = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +00001742
1743 // Generate each type info
1744 //
1745 // Note: First type info is not used.
1746 for (unsigned i = 0; i <= numTypeInfos; ++i) {
1747 structVals.clear();
1748 structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
1749 nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001750
Chris Lattner626ab1c2011-04-08 18:02:51 +00001751 typeInfoNameBuilder.str("");
1752 typeInfoNameBuilder << baseStr << i;
1753 typeInfoName = typeInfoNameBuilder.str();
1754
1755 // Note: Does not seem to work without allocation
1756 nextGlobal =
1757 new llvm::GlobalVariable(module,
1758 ourTypeInfoType,
1759 true,
1760 llvm::GlobalValue::ExternalLinkage,
1761 nextStruct,
1762 typeInfoName);
1763
1764 ourTypeInfoNames.push_back(typeInfoName);
1765 ourTypeInfoNamesIndex[i] = typeInfoName;
1766 }
1767
1768 ArgNames argNames;
1769 ArgTypes argTypes;
Garrison Venn64cfcef2011-04-10 14:06:52 +00001770 llvm::Function *funct = NULL;
Chris Lattner626ab1c2011-04-08 18:02:51 +00001771
1772 // print32Int
1773
Chris Lattner77613d42011-07-18 04:52:09 +00001774 llvm::Type *retType = builder.getVoidTy();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001775
1776 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001777 argTypes.push_back(builder.getInt32Ty());
1778 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 "print32Int",
1787 llvm::Function::ExternalLinkage,
1788 true,
1789 false);
1790
1791 // print64Int
1792
1793 retType = builder.getVoidTy();
1794
1795 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001796 argTypes.push_back(builder.getInt64Ty());
1797 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001798
1799 argNames.clear();
1800
1801 createFunction(module,
1802 retType,
1803 argTypes,
1804 argNames,
1805 "print64Int",
1806 llvm::Function::ExternalLinkage,
1807 true,
1808 false);
1809
1810 // printStr
1811
1812 retType = builder.getVoidTy();
1813
1814 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001815 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001816
1817 argNames.clear();
1818
1819 createFunction(module,
1820 retType,
1821 argTypes,
1822 argNames,
1823 "printStr",
1824 llvm::Function::ExternalLinkage,
1825 true,
1826 false);
1827
1828 // throwCppException
1829
1830 retType = builder.getVoidTy();
1831
1832 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001833 argTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001834
1835 argNames.clear();
1836
1837 createFunction(module,
1838 retType,
1839 argTypes,
1840 argNames,
1841 "throwCppException",
1842 llvm::Function::ExternalLinkage,
1843 true,
1844 false);
1845
1846 // deleteOurException
1847
1848 retType = builder.getVoidTy();
1849
1850 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001851 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001852
1853 argNames.clear();
1854
1855 createFunction(module,
1856 retType,
1857 argTypes,
1858 argNames,
1859 "deleteOurException",
1860 llvm::Function::ExternalLinkage,
1861 true,
1862 false);
1863
1864 // createOurException
1865
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001866 retType = builder.getInt8PtrTy();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001867
1868 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001869 argTypes.push_back(builder.getInt32Ty());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001870
1871 argNames.clear();
1872
1873 createFunction(module,
1874 retType,
1875 argTypes,
1876 argNames,
1877 "createOurException",
1878 llvm::Function::ExternalLinkage,
1879 true,
1880 false);
1881
1882 // _Unwind_RaiseException
1883
1884 retType = builder.getInt32Ty();
1885
1886 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001887 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001888
1889 argNames.clear();
1890
1891 funct = createFunction(module,
1892 retType,
1893 argTypes,
1894 argNames,
1895 "_Unwind_RaiseException",
1896 llvm::Function::ExternalLinkage,
1897 true,
1898 false);
1899
1900 funct->addFnAttr(llvm::Attribute::NoReturn);
1901
1902 // _Unwind_Resume
1903
1904 retType = builder.getInt32Ty();
1905
1906 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001907 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001908
1909 argNames.clear();
1910
1911 funct = createFunction(module,
1912 retType,
1913 argTypes,
1914 argNames,
1915 "_Unwind_Resume",
1916 llvm::Function::ExternalLinkage,
1917 true,
1918 false);
1919
1920 funct->addFnAttr(llvm::Attribute::NoReturn);
1921
1922 // ourPersonality
1923
1924 retType = builder.getInt32Ty();
1925
1926 argTypes.clear();
Garrison Vennc0f33cb2011-07-12 15:34:42 +00001927 argTypes.push_back(builder.getInt32Ty());
1928 argTypes.push_back(builder.getInt32Ty());
1929 argTypes.push_back(builder.getInt64Ty());
1930 argTypes.push_back(builder.getInt8PtrTy());
1931 argTypes.push_back(builder.getInt8PtrTy());
Chris Lattner626ab1c2011-04-08 18:02:51 +00001932
1933 argNames.clear();
1934
1935 createFunction(module,
1936 retType,
1937 argTypes,
1938 argNames,
1939 "ourPersonality",
1940 llvm::Function::ExternalLinkage,
1941 true,
1942 false);
1943
1944 // llvm.eh.selector intrinsic
1945
1946 getDeclaration(&module, llvm::Intrinsic::eh_selector);
1947
1948 // llvm.eh.exception intrinsic
1949
1950 getDeclaration(&module, llvm::Intrinsic::eh_exception);
1951
1952 // llvm.eh.typeid.for intrinsic
1953
1954 getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001955}
1956
1957
Chris Lattner626ab1c2011-04-08 18:02:51 +00001958//===----------------------------------------------------------------------===//
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001959// Main test driver code.
Chris Lattner626ab1c2011-04-08 18:02:51 +00001960//===----------------------------------------------------------------------===//
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001961
1962/// Demo main routine which takes the type info types to throw. A test will
1963/// be run for each given type info type. While type info types with the value
1964/// of -1 will trigger a foreign C++ exception to be thrown; type info types
1965/// <= 6 and >= 1 will be caught by test functions; and type info types > 6
1966/// will result in exceptions which pass through to the test harness. All other
1967/// type info types are not supported and could cause a crash.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001968int main(int argc, char *argv[]) {
Chris Lattner626ab1c2011-04-08 18:02:51 +00001969 if (argc == 1) {
1970 fprintf(stderr,
1971 "\nUsage: ExceptionDemo <exception type to throw> "
1972 "[<type 2>...<type n>].\n"
1973 " Each type must have the value of 1 - 6 for "
1974 "generated exceptions to be caught;\n"
1975 " the value -1 for foreign C++ exceptions to be "
1976 "generated and thrown;\n"
1977 " or the values > 6 for exceptions to be ignored.\n"
1978 "\nTry: ExceptionDemo 2 3 7 -1\n"
1979 " for a full test.\n\n");
1980 return(0);
1981 }
Garrison Venna2c2f1a2010-02-09 23:22:43 +00001982
Chris Lattner626ab1c2011-04-08 18:02:51 +00001983 // If not set, exception handling will not be turned on
1984 llvm::JITExceptionHandling = true;
1985
1986 llvm::InitializeNativeTarget();
Garrison Venn64cfcef2011-04-10 14:06:52 +00001987 llvm::LLVMContext &context = llvm::getGlobalContext();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001988 llvm::IRBuilder<> theBuilder(context);
1989
1990 // Make the module, which holds all the code.
Garrison Venn64cfcef2011-04-10 14:06:52 +00001991 llvm::Module *module = new llvm::Module("my cool jit", context);
Chris Lattner626ab1c2011-04-08 18:02:51 +00001992
1993 // Build engine with JIT
1994 llvm::EngineBuilder factory(module);
1995 factory.setEngineKind(llvm::EngineKind::JIT);
1996 factory.setAllocateGVsWithCode(false);
Garrison Venn64cfcef2011-04-10 14:06:52 +00001997 llvm::ExecutionEngine *executionEngine = factory.create();
Chris Lattner626ab1c2011-04-08 18:02:51 +00001998
1999 {
2000 llvm::FunctionPassManager fpm(module);
2001
2002 // Set up the optimizer pipeline.
2003 // Start with registering info about how the
2004 // target lays out data structures.
2005 fpm.add(new llvm::TargetData(*executionEngine->getTargetData()));
2006
2007 // Optimizations turned on
2008#ifdef ADD_OPT_PASSES
2009
2010 // Basic AliasAnslysis support for GVN.
2011 fpm.add(llvm::createBasicAliasAnalysisPass());
2012
2013 // Promote allocas to registers.
2014 fpm.add(llvm::createPromoteMemoryToRegisterPass());
2015
2016 // Do simple "peephole" optimizations and bit-twiddling optzns.
2017 fpm.add(llvm::createInstructionCombiningPass());
2018
2019 // Reassociate expressions.
2020 fpm.add(llvm::createReassociatePass());
2021
2022 // Eliminate Common SubExpressions.
2023 fpm.add(llvm::createGVNPass());
2024
2025 // Simplify the control flow graph (deleting unreachable
2026 // blocks, etc).
2027 fpm.add(llvm::createCFGSimplificationPass());
2028#endif // ADD_OPT_PASSES
2029
2030 fpm.doInitialization();
2031
2032 // Generate test code using function throwCppException(...) as
2033 // the function which throws foreign exceptions.
Garrison Venn64cfcef2011-04-10 14:06:52 +00002034 llvm::Function *toRun =
Garrison Venn85500712011-09-22 15:45:14 +00002035 createUnwindExceptionTest(*module,
2036 theBuilder,
2037 fpm,
2038 "throwCppException");
Chris Lattner626ab1c2011-04-08 18:02:51 +00002039
2040 fprintf(stderr, "\nBegin module dump:\n\n");
2041
2042 module->dump();
2043
2044 fprintf(stderr, "\nEnd module dump:\n");
2045
2046 fprintf(stderr, "\n\nBegin Test:\n");
2047
2048 for (int i = 1; i < argc; ++i) {
2049 // Run test for each argument whose value is the exception
2050 // type to throw.
2051 runExceptionThrow(executionEngine,
2052 toRun,
2053 (unsigned) strtoul(argv[i], NULL, 10));
2054 }
2055
2056 fprintf(stderr, "\nEnd Test:\n\n");
2057 }
2058
2059 delete executionEngine;
2060
2061 return 0;
Garrison Venna2c2f1a2010-02-09 23:22:43 +00002062}
2063