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