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