AsmWriter.cpp revision 3518175d4256df88fcaf133c0ed9fb166db7993c
1//===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===// 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// This library implements the functionality defined in llvm/Assembly/Writer.h 11// 12// Note that these routines must be extremely tolerant of various errors in the 13// LLVM code, because it can be used for debugging transformations. 14// 15//===----------------------------------------------------------------------===// 16 17#include "llvm/Assembly/Writer.h" 18#include "llvm/Assembly/PrintModulePass.h" 19#include "llvm/Assembly/AsmAnnotationWriter.h" 20#include "llvm/CallingConv.h" 21#include "llvm/Constants.h" 22#include "llvm/DerivedTypes.h" 23#include "llvm/InlineAsm.h" 24#include "llvm/Instruction.h" 25#include "llvm/Instructions.h" 26#include "llvm/Module.h" 27#include "llvm/ValueSymbolTable.h" 28#include "llvm/TypeSymbolTable.h" 29#include "llvm/ADT/DenseMap.h" 30#include "llvm/ADT/StringExtras.h" 31#include "llvm/ADT/STLExtras.h" 32#include "llvm/Support/CFG.h" 33#include "llvm/Support/MathExtras.h" 34#include "llvm/Support/raw_ostream.h" 35#include <algorithm> 36#include <cctype> 37using namespace llvm; 38 39// Make virtual table appear in this compilation unit. 40AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {} 41 42char PrintModulePass::ID = 0; 43static RegisterPass<PrintModulePass> 44X("printm", "Print module to stderr"); 45char PrintFunctionPass::ID = 0; 46static RegisterPass<PrintFunctionPass> 47Y("print","Print function to stderr"); 48 49 50//===----------------------------------------------------------------------===// 51// Helper Functions 52//===----------------------------------------------------------------------===// 53 54static const Module *getModuleFromVal(const Value *V) { 55 if (const Argument *MA = dyn_cast<Argument>(V)) 56 return MA->getParent() ? MA->getParent()->getParent() : 0; 57 58 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 59 return BB->getParent() ? BB->getParent()->getParent() : 0; 60 61 if (const Instruction *I = dyn_cast<Instruction>(V)) { 62 const Function *M = I->getParent() ? I->getParent()->getParent() : 0; 63 return M ? M->getParent() : 0; 64 } 65 66 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 67 return GV->getParent(); 68 return 0; 69} 70 71 72/// NameNeedsQuotes - Return true if the specified llvm name should be wrapped 73/// with ""'s. 74static std::string QuoteNameIfNeeded(const std::string &Name) { 75 std::string result; 76 bool needsQuotes = Name[0] >= '0' && Name[0] <= '9'; 77 // Scan the name to see if it needs quotes and to replace funky chars with 78 // their octal equivalent. 79 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 80 char C = Name[i]; 81 assert(C != '"' && "Illegal character in LLVM value name!"); 82 if (isalnum(C) || C == '-' || C == '.' || C == '_') 83 result += C; 84 else if (C == '\\') { 85 needsQuotes = true; 86 result += "\\\\"; 87 } else if (isprint(C)) { 88 needsQuotes = true; 89 result += C; 90 } else { 91 needsQuotes = true; 92 result += "\\"; 93 char hex1 = (C >> 4) & 0x0F; 94 if (hex1 < 10) 95 result += hex1 + '0'; 96 else 97 result += hex1 - 10 + 'A'; 98 char hex2 = C & 0x0F; 99 if (hex2 < 10) 100 result += hex2 + '0'; 101 else 102 result += hex2 - 10 + 'A'; 103 } 104 } 105 if (needsQuotes) { 106 result.insert(0,"\""); 107 result += '"'; 108 } 109 return result; 110} 111 112/// getLLVMName - Turn the specified string into an 'LLVM name', which is 113/// surrounded with ""'s and escaped if it has special chars in it. 114static std::string getLLVMName(const std::string &Name) { 115 assert(!Name.empty() && "Cannot get empty name!"); 116 return QuoteNameIfNeeded(Name); 117} 118 119enum PrefixType { 120 GlobalPrefix, 121 LabelPrefix, 122 LocalPrefix 123}; 124 125/// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either 126/// prefixed with % (if the string only contains simple characters) or is 127/// surrounded with ""'s (if it has special chars in it). Print it out. 128static void PrintLLVMName(raw_ostream &OS, const char *NameStr, 129 unsigned NameLen, PrefixType Prefix) { 130 assert(NameStr && "Cannot get empty name!"); 131 switch (Prefix) { 132 default: assert(0 && "Bad prefix!"); 133 case GlobalPrefix: OS << '@'; break; 134 case LabelPrefix: break; 135 case LocalPrefix: OS << '%'; break; 136 } 137 138 // Scan the name to see if it needs quotes first. 139 bool NeedsQuotes = NameStr[0] >= '0' && NameStr[0] <= '9'; 140 if (!NeedsQuotes) { 141 for (unsigned i = 0; i != NameLen; ++i) { 142 char C = NameStr[i]; 143 if (!isalnum(C) && C != '-' && C != '.' && C != '_') { 144 NeedsQuotes = true; 145 break; 146 } 147 } 148 } 149 150 // If we didn't need any quotes, just write out the name in one blast. 151 if (!NeedsQuotes) { 152 OS.write(NameStr, NameLen); 153 return; 154 } 155 156 // Okay, we need quotes. Output the quotes and escape any scary characters as 157 // needed. 158 OS << '"'; 159 for (unsigned i = 0; i != NameLen; ++i) { 160 char C = NameStr[i]; 161 assert(C != '"' && "Illegal character in LLVM value name!"); 162 if (C == '\\') { 163 OS << "\\\\"; 164 } else if (isprint(C)) { 165 OS << C; 166 } else { 167 OS << '\\'; 168 char hex1 = (C >> 4) & 0x0F; 169 if (hex1 < 10) 170 OS << (char)(hex1 + '0'); 171 else 172 OS << (char)(hex1 - 10 + 'A'); 173 char hex2 = C & 0x0F; 174 if (hex2 < 10) 175 OS << (char)(hex2 + '0'); 176 else 177 OS << (char)(hex2 - 10 + 'A'); 178 } 179 } 180 OS << '"'; 181} 182 183/// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either 184/// prefixed with % (if the string only contains simple characters) or is 185/// surrounded with ""'s (if it has special chars in it). Print it out. 186static void PrintLLVMName(raw_ostream &OS, const Value *V) { 187 PrintLLVMName(OS, V->getNameStart(), V->getNameLen(), 188 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix); 189} 190 191 192 193//===----------------------------------------------------------------------===// 194// SlotTracker Class: Enumerate slot numbers for unnamed values 195//===----------------------------------------------------------------------===// 196 197namespace { 198 199/// This class provides computation of slot numbers for LLVM Assembly writing. 200/// 201class SlotTracker { 202public: 203 /// ValueMap - A mapping of Values to slot numbers 204 typedef DenseMap<const Value*, unsigned> ValueMap; 205 206private: 207 /// TheModule - The module for which we are holding slot numbers 208 const Module* TheModule; 209 210 /// TheFunction - The function for which we are holding slot numbers 211 const Function* TheFunction; 212 bool FunctionProcessed; 213 214 /// mMap - The TypePlanes map for the module level data 215 ValueMap mMap; 216 unsigned mNext; 217 218 /// fMap - The TypePlanes map for the function level data 219 ValueMap fMap; 220 unsigned fNext; 221 222public: 223 /// Construct from a module 224 explicit SlotTracker(const Module *M); 225 /// Construct from a function, starting out in incorp state. 226 explicit SlotTracker(const Function *F); 227 228 /// Return the slot number of the specified value in it's type 229 /// plane. If something is not in the SlotTracker, return -1. 230 int getLocalSlot(const Value *V); 231 int getGlobalSlot(const GlobalValue *V); 232 233 /// If you'd like to deal with a function instead of just a module, use 234 /// this method to get its data into the SlotTracker. 235 void incorporateFunction(const Function *F) { 236 TheFunction = F; 237 FunctionProcessed = false; 238 } 239 240 /// After calling incorporateFunction, use this method to remove the 241 /// most recently incorporated function from the SlotTracker. This 242 /// will reset the state of the machine back to just the module contents. 243 void purgeFunction(); 244 245 // Implementation Details 246private: 247 /// This function does the actual initialization. 248 inline void initialize(); 249 250 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 251 void CreateModuleSlot(const GlobalValue *V); 252 253 /// CreateFunctionSlot - Insert the specified Value* into the slot table. 254 void CreateFunctionSlot(const Value *V); 255 256 /// Add all of the module level global variables (and their initializers) 257 /// and function declarations, but not the contents of those functions. 258 void processModule(); 259 260 /// Add all of the functions arguments, basic blocks, and instructions 261 void processFunction(); 262 263 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT 264 void operator=(const SlotTracker &); // DO NOT IMPLEMENT 265}; 266 267} // end anonymous namespace 268 269 270static SlotTracker *createSlotTracker(const Value *V) { 271 if (const Argument *FA = dyn_cast<Argument>(V)) 272 return new SlotTracker(FA->getParent()); 273 274 if (const Instruction *I = dyn_cast<Instruction>(V)) 275 return new SlotTracker(I->getParent()->getParent()); 276 277 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 278 return new SlotTracker(BB->getParent()); 279 280 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) 281 return new SlotTracker(GV->getParent()); 282 283 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 284 return new SlotTracker(GA->getParent()); 285 286 if (const Function *Func = dyn_cast<Function>(V)) 287 return new SlotTracker(Func); 288 289 return 0; 290} 291 292#if 0 293#define ST_DEBUG(X) cerr << X 294#else 295#define ST_DEBUG(X) 296#endif 297 298// Module level constructor. Causes the contents of the Module (sans functions) 299// to be added to the slot table. 300SlotTracker::SlotTracker(const Module *M) 301 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) { 302} 303 304// Function level constructor. Causes the contents of the Module and the one 305// function provided to be added to the slot table. 306SlotTracker::SlotTracker(const Function *F) 307 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false), 308 mNext(0), fNext(0) { 309} 310 311inline void SlotTracker::initialize() { 312 if (TheModule) { 313 processModule(); 314 TheModule = 0; ///< Prevent re-processing next time we're called. 315 } 316 317 if (TheFunction && !FunctionProcessed) 318 processFunction(); 319} 320 321// Iterate through all the global variables, functions, and global 322// variable initializers and create slots for them. 323void SlotTracker::processModule() { 324 ST_DEBUG("begin processModule!\n"); 325 326 // Add all of the unnamed global variables to the value table. 327 for (Module::const_global_iterator I = TheModule->global_begin(), 328 E = TheModule->global_end(); I != E; ++I) 329 if (!I->hasName()) 330 CreateModuleSlot(I); 331 332 // Add all the unnamed functions to the table. 333 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 334 I != E; ++I) 335 if (!I->hasName()) 336 CreateModuleSlot(I); 337 338 ST_DEBUG("end processModule!\n"); 339} 340 341 342// Process the arguments, basic blocks, and instructions of a function. 343void SlotTracker::processFunction() { 344 ST_DEBUG("begin processFunction!\n"); 345 fNext = 0; 346 347 // Add all the function arguments with no names. 348 for(Function::const_arg_iterator AI = TheFunction->arg_begin(), 349 AE = TheFunction->arg_end(); AI != AE; ++AI) 350 if (!AI->hasName()) 351 CreateFunctionSlot(AI); 352 353 ST_DEBUG("Inserting Instructions:\n"); 354 355 // Add all of the basic blocks and instructions with no names. 356 for (Function::const_iterator BB = TheFunction->begin(), 357 E = TheFunction->end(); BB != E; ++BB) { 358 if (!BB->hasName()) 359 CreateFunctionSlot(BB); 360 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) 361 if (I->getType() != Type::VoidTy && !I->hasName()) 362 CreateFunctionSlot(I); 363 } 364 365 FunctionProcessed = true; 366 367 ST_DEBUG("end processFunction!\n"); 368} 369 370/// Clean up after incorporating a function. This is the only way to get out of 371/// the function incorporation state that affects get*Slot/Create*Slot. Function 372/// incorporation state is indicated by TheFunction != 0. 373void SlotTracker::purgeFunction() { 374 ST_DEBUG("begin purgeFunction!\n"); 375 fMap.clear(); // Simply discard the function level map 376 TheFunction = 0; 377 FunctionProcessed = false; 378 ST_DEBUG("end purgeFunction!\n"); 379} 380 381/// getGlobalSlot - Get the slot number of a global value. 382int SlotTracker::getGlobalSlot(const GlobalValue *V) { 383 // Check for uninitialized state and do lazy initialization. 384 initialize(); 385 386 // Find the type plane in the module map 387 ValueMap::iterator MI = mMap.find(V); 388 return MI == mMap.end() ? -1 : MI->second; 389} 390 391 392/// getLocalSlot - Get the slot number for a value that is local to a function. 393int SlotTracker::getLocalSlot(const Value *V) { 394 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!"); 395 396 // Check for uninitialized state and do lazy initialization. 397 initialize(); 398 399 ValueMap::iterator FI = fMap.find(V); 400 return FI == fMap.end() ? -1 : FI->second; 401} 402 403 404/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 405void SlotTracker::CreateModuleSlot(const GlobalValue *V) { 406 assert(V && "Can't insert a null Value into SlotTracker!"); 407 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!"); 408 assert(!V->hasName() && "Doesn't need a slot!"); 409 410 unsigned DestSlot = mNext++; 411 mMap[V] = DestSlot; 412 413 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 414 DestSlot << " ["); 415 // G = Global, F = Function, A = Alias, o = other 416 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' : 417 (isa<Function>(V) ? 'F' : 418 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n"); 419} 420 421 422/// CreateSlot - Create a new slot for the specified value if it has no name. 423void SlotTracker::CreateFunctionSlot(const Value *V) { 424 assert(V->getType() != Type::VoidTy && !V->hasName() && 425 "Doesn't need a slot!"); 426 427 unsigned DestSlot = fNext++; 428 fMap[V] = DestSlot; 429 430 // G = Global, F = Function, o = other 431 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 432 DestSlot << " [o]\n"); 433} 434 435 436 437//===----------------------------------------------------------------------===// 438// AsmWriter Implementation 439//===----------------------------------------------------------------------===// 440 441static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 442 std::map<const Type *, std::string> &TypeTable, 443 SlotTracker *Machine); 444 445 446 447/// fillTypeNameTable - If the module has a symbol table, take all global types 448/// and stuff their names into the TypeNames map. 449/// 450static void fillTypeNameTable(const Module *M, 451 std::map<const Type *, std::string> &TypeNames) { 452 if (!M) return; 453 const TypeSymbolTable &ST = M->getTypeSymbolTable(); 454 TypeSymbolTable::const_iterator TI = ST.begin(); 455 for (; TI != ST.end(); ++TI) { 456 // As a heuristic, don't insert pointer to primitive types, because 457 // they are used too often to have a single useful name. 458 // 459 const Type *Ty = cast<Type>(TI->second); 460 if (!isa<PointerType>(Ty) || 461 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() || 462 !cast<PointerType>(Ty)->getElementType()->isInteger() || 463 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType())) 464 TypeNames.insert(std::make_pair(Ty, '%' + getLLVMName(TI->first))); 465 } 466} 467 468 469 470static void calcTypeName(const Type *Ty, 471 std::vector<const Type *> &TypeStack, 472 std::map<const Type *, std::string> &TypeNames, 473 std::string &Result) { 474 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) { 475 Result += Ty->getDescription(); // Base case 476 return; 477 } 478 479 // Check to see if the type is named. 480 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty); 481 if (I != TypeNames.end()) { 482 Result += I->second; 483 return; 484 } 485 486 if (isa<OpaqueType>(Ty)) { 487 Result += "opaque"; 488 return; 489 } 490 491 // Check to see if the Type is already on the stack... 492 unsigned Slot = 0, CurSize = TypeStack.size(); 493 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type 494 495 // This is another base case for the recursion. In this case, we know 496 // that we have looped back to a type that we have previously visited. 497 // Generate the appropriate upreference to handle this. 498 if (Slot < CurSize) { 499 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference 500 return; 501 } 502 503 TypeStack.push_back(Ty); // Recursive case: Add us to the stack.. 504 505 switch (Ty->getTypeID()) { 506 case Type::IntegerTyID: { 507 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth(); 508 Result += "i" + utostr(BitWidth); 509 break; 510 } 511 case Type::FunctionTyID: { 512 const FunctionType *FTy = cast<FunctionType>(Ty); 513 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result); 514 Result += " ("; 515 for (FunctionType::param_iterator I = FTy->param_begin(), 516 E = FTy->param_end(); I != E; ++I) { 517 if (I != FTy->param_begin()) 518 Result += ", "; 519 calcTypeName(*I, TypeStack, TypeNames, Result); 520 } 521 if (FTy->isVarArg()) { 522 if (FTy->getNumParams()) Result += ", "; 523 Result += "..."; 524 } 525 Result += ")"; 526 break; 527 } 528 case Type::StructTyID: { 529 const StructType *STy = cast<StructType>(Ty); 530 if (STy->isPacked()) 531 Result += '<'; 532 Result += "{ "; 533 for (StructType::element_iterator I = STy->element_begin(), 534 E = STy->element_end(); I != E; ++I) { 535 if (I != STy->element_begin()) 536 Result += ", "; 537 calcTypeName(*I, TypeStack, TypeNames, Result); 538 } 539 Result += " }"; 540 if (STy->isPacked()) 541 Result += '>'; 542 break; 543 } 544 case Type::PointerTyID: { 545 const PointerType *PTy = cast<PointerType>(Ty); 546 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result); 547 if (unsigned AddressSpace = PTy->getAddressSpace()) 548 Result += " addrspace(" + utostr(AddressSpace) + ")"; 549 Result += "*"; 550 break; 551 } 552 case Type::ArrayTyID: { 553 const ArrayType *ATy = cast<ArrayType>(Ty); 554 Result += "[" + utostr(ATy->getNumElements()) + " x "; 555 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result); 556 Result += "]"; 557 break; 558 } 559 case Type::VectorTyID: { 560 const VectorType *PTy = cast<VectorType>(Ty); 561 Result += "<" + utostr(PTy->getNumElements()) + " x "; 562 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result); 563 Result += ">"; 564 break; 565 } 566 case Type::OpaqueTyID: 567 Result += "opaque"; 568 break; 569 default: 570 Result += "<unrecognized-type>"; 571 break; 572 } 573 574 TypeStack.pop_back(); // Remove self from stack... 575} 576 577 578/// printTypeInt - The internal guts of printing out a type that has a 579/// potentially named portion. 580/// 581static void printTypeInt(raw_ostream &Out, const Type *Ty, 582 std::map<const Type *, std::string> &TypeNames) { 583 // Primitive types always print out their description, regardless of whether 584 // they have been named or not. 585 // 586 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) { 587 Out << Ty->getDescription(); 588 return; 589 } 590 591 // Check to see if the type is named. 592 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty); 593 if (I != TypeNames.end()) { 594 Out << I->second; 595 return; 596 } 597 598 // Otherwise we have a type that has not been named but is a derived type. 599 // Carefully recurse the type hierarchy to print out any contained symbolic 600 // names. 601 // 602 std::vector<const Type *> TypeStack; 603 std::string TypeName; 604 calcTypeName(Ty, TypeStack, TypeNames, TypeName); 605 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use 606 Out << TypeName; 607} 608 609 610/// WriteTypeSymbolic - This attempts to write the specified type as a symbolic 611/// type, iff there is an entry in the modules symbol table for the specified 612/// type or one of it's component types. This is slower than a simple x << Type 613/// 614void llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty, 615 const Module *M) { 616 raw_os_ostream RO(Out); 617 WriteTypeSymbolic(RO, Ty, M); 618} 619 620void llvm::WriteTypeSymbolic(raw_ostream &Out, const Type *Ty, const Module *M){ 621 Out << ' '; 622 623 // If they want us to print out a type, but there is no context, we can't 624 // print it symbolically. 625 if (!M) { 626 Out << Ty->getDescription(); 627 } else { 628 std::map<const Type *, std::string> TypeNames; 629 fillTypeNameTable(M, TypeNames); 630 printTypeInt(Out, Ty, TypeNames); 631 } 632} 633 634// PrintEscapedString - Print each character of the specified string, escaping 635// it if it is not printable or if it is an escape char. 636static void PrintEscapedString(const std::string &Str, raw_ostream &Out) { 637 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 638 unsigned char C = Str[i]; 639 if (isprint(C) && C != '"' && C != '\\') { 640 Out << C; 641 } else { 642 Out << '\\' 643 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A')) 644 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A')); 645 } 646 } 647} 648 649static const char *getPredicateText(unsigned predicate) { 650 const char * pred = "unknown"; 651 switch (predicate) { 652 case FCmpInst::FCMP_FALSE: pred = "false"; break; 653 case FCmpInst::FCMP_OEQ: pred = "oeq"; break; 654 case FCmpInst::FCMP_OGT: pred = "ogt"; break; 655 case FCmpInst::FCMP_OGE: pred = "oge"; break; 656 case FCmpInst::FCMP_OLT: pred = "olt"; break; 657 case FCmpInst::FCMP_OLE: pred = "ole"; break; 658 case FCmpInst::FCMP_ONE: pred = "one"; break; 659 case FCmpInst::FCMP_ORD: pred = "ord"; break; 660 case FCmpInst::FCMP_UNO: pred = "uno"; break; 661 case FCmpInst::FCMP_UEQ: pred = "ueq"; break; 662 case FCmpInst::FCMP_UGT: pred = "ugt"; break; 663 case FCmpInst::FCMP_UGE: pred = "uge"; break; 664 case FCmpInst::FCMP_ULT: pred = "ult"; break; 665 case FCmpInst::FCMP_ULE: pred = "ule"; break; 666 case FCmpInst::FCMP_UNE: pred = "une"; break; 667 case FCmpInst::FCMP_TRUE: pred = "true"; break; 668 case ICmpInst::ICMP_EQ: pred = "eq"; break; 669 case ICmpInst::ICMP_NE: pred = "ne"; break; 670 case ICmpInst::ICMP_SGT: pred = "sgt"; break; 671 case ICmpInst::ICMP_SGE: pred = "sge"; break; 672 case ICmpInst::ICMP_SLT: pred = "slt"; break; 673 case ICmpInst::ICMP_SLE: pred = "sle"; break; 674 case ICmpInst::ICMP_UGT: pred = "ugt"; break; 675 case ICmpInst::ICMP_UGE: pred = "uge"; break; 676 case ICmpInst::ICMP_ULT: pred = "ult"; break; 677 case ICmpInst::ICMP_ULE: pred = "ule"; break; 678 } 679 return pred; 680} 681 682static void WriteConstantInt(raw_ostream &Out, const Constant *CV, 683 std::map<const Type *, std::string> &TypeTable, 684 SlotTracker *Machine) { 685 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 686 if (CI->getType() == Type::Int1Ty) { 687 Out << (CI->getZExtValue() ? "true" : "false"); 688 return; 689 } 690 Out << CI->getValue(); 691 return; 692 } 693 694 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 695 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble || 696 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) { 697 // We would like to output the FP constant value in exponential notation, 698 // but we cannot do this if doing so will lose precision. Check here to 699 // make sure that we only output it in exponential format if we can parse 700 // the value back and get the same value. 701 // 702 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble; 703 double Val = isDouble ? CFP->getValueAPF().convertToDouble() : 704 CFP->getValueAPF().convertToFloat(); 705 std::string StrVal = ftostr(CFP->getValueAPF()); 706 707 // Check to make sure that the stringized number is not some string like 708 // "Inf" or NaN, that atof will accept, but the lexer will not. Check 709 // that the string matches the "[-+]?[0-9]" regex. 710 // 711 if ((StrVal[0] >= '0' && StrVal[0] <= '9') || 712 ((StrVal[0] == '-' || StrVal[0] == '+') && 713 (StrVal[1] >= '0' && StrVal[1] <= '9'))) { 714 // Reparse stringized version! 715 if (atof(StrVal.c_str()) == Val) { 716 Out << StrVal; 717 return; 718 } 719 } 720 // Otherwise we could not reparse it to exactly the same value, so we must 721 // output the string in hexadecimal format! 722 assert(sizeof(double) == sizeof(uint64_t) && 723 "assuming that double is 64 bits!"); 724 Out << "0x" << utohexstr(DoubleToBits(Val)); 725 return; 726 } 727 728 // Some form of long double. These appear as a magic letter identifying 729 // the type, then a fixed number of hex digits. 730 Out << "0x"; 731 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) 732 Out << 'K'; 733 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) 734 Out << 'L'; 735 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) 736 Out << 'M'; 737 else 738 assert(0 && "Unsupported floating point type"); 739 // api needed to prevent premature destruction 740 APInt api = CFP->getValueAPF().convertToAPInt(); 741 const uint64_t* p = api.getRawData(); 742 uint64_t word = *p; 743 int shiftcount=60; 744 int width = api.getBitWidth(); 745 for (int j=0; j<width; j+=4, shiftcount-=4) { 746 unsigned int nibble = (word>>shiftcount) & 15; 747 if (nibble < 10) 748 Out << (unsigned char)(nibble + '0'); 749 else 750 Out << (unsigned char)(nibble - 10 + 'A'); 751 if (shiftcount == 0 && j+4 < width) { 752 word = *(++p); 753 shiftcount = 64; 754 if (width-j-4 < 64) 755 shiftcount = width-j-4; 756 } 757 } 758 return; 759 } 760 761 if (isa<ConstantAggregateZero>(CV)) { 762 Out << "zeroinitializer"; 763 return; 764 } 765 766 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) { 767 // As a special case, print the array as a string if it is an array of 768 // i8 with ConstantInt values. 769 // 770 const Type *ETy = CA->getType()->getElementType(); 771 if (CA->isString()) { 772 Out << "c\""; 773 PrintEscapedString(CA->getAsString(), Out); 774 Out << '"'; 775 } else { // Cannot output in string format... 776 Out << '['; 777 if (CA->getNumOperands()) { 778 Out << ' '; 779 printTypeInt(Out, ETy, TypeTable); 780 WriteAsOperandInternal(Out, CA->getOperand(0), 781 TypeTable, Machine); 782 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) { 783 Out << ", "; 784 printTypeInt(Out, ETy, TypeTable); 785 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine); 786 } 787 } 788 Out << " ]"; 789 } 790 return; 791 } 792 793 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) { 794 if (CS->getType()->isPacked()) 795 Out << '<'; 796 Out << '{'; 797 unsigned N = CS->getNumOperands(); 798 if (N) { 799 Out << ' '; 800 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable); 801 802 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine); 803 804 for (unsigned i = 1; i < N; i++) { 805 Out << ", "; 806 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable); 807 808 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine); 809 } 810 } 811 812 Out << " }"; 813 if (CS->getType()->isPacked()) 814 Out << '>'; 815 return; 816 } 817 818 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) { 819 const Type *ETy = CP->getType()->getElementType(); 820 assert(CP->getNumOperands() > 0 && 821 "Number of operands for a PackedConst must be > 0"); 822 Out << "< "; 823 printTypeInt(Out, ETy, TypeTable); 824 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine); 825 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) { 826 Out << ", "; 827 printTypeInt(Out, ETy, TypeTable); 828 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine); 829 } 830 Out << " >"; 831 return; 832 } 833 834 if (isa<ConstantPointerNull>(CV)) { 835 Out << "null"; 836 return; 837 } 838 839 if (isa<UndefValue>(CV)) { 840 Out << "undef"; 841 return; 842 } 843 844 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 845 Out << CE->getOpcodeName(); 846 if (CE->isCompare()) 847 Out << ' ' << getPredicateText(CE->getPredicate()); 848 Out << " ("; 849 850 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) { 851 printTypeInt(Out, (*OI)->getType(), TypeTable); 852 WriteAsOperandInternal(Out, *OI, TypeTable, Machine); 853 if (OI+1 != CE->op_end()) 854 Out << ", "; 855 } 856 857 if (CE->hasIndices()) { 858 const SmallVector<unsigned, 4> &Indices = CE->getIndices(); 859 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 860 Out << ", " << Indices[i]; 861 } 862 863 if (CE->isCast()) { 864 Out << " to "; 865 printTypeInt(Out, CE->getType(), TypeTable); 866 } 867 868 Out << ')'; 869 return; 870 } 871 872 Out << "<placeholder or erroneous Constant>"; 873} 874 875 876/// WriteAsOperand - Write the name of the specified value out to the specified 877/// ostream. This can be useful when you just want to print int %reg126, not 878/// the whole instruction that generated it. 879/// 880static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 881 std::map<const Type*, std::string> &TypeTable, 882 SlotTracker *Machine) { 883 Out << ' '; 884 if (V->hasName()) { 885 PrintLLVMName(Out, V); 886 return; 887 } 888 889 const Constant *CV = dyn_cast<Constant>(V); 890 if (CV && !isa<GlobalValue>(CV)) { 891 WriteConstantInt(Out, CV, TypeTable, Machine); 892 return; 893 } 894 895 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 896 Out << "asm "; 897 if (IA->hasSideEffects()) 898 Out << "sideeffect "; 899 Out << '"'; 900 PrintEscapedString(IA->getAsmString(), Out); 901 Out << "\", \""; 902 PrintEscapedString(IA->getConstraintString(), Out); 903 Out << '"'; 904 return; 905 } 906 907 char Prefix = '%'; 908 int Slot; 909 if (Machine) { 910 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 911 Slot = Machine->getGlobalSlot(GV); 912 Prefix = '@'; 913 } else { 914 Slot = Machine->getLocalSlot(V); 915 } 916 } else { 917 Machine = createSlotTracker(V); 918 if (Machine) { 919 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 920 Slot = Machine->getGlobalSlot(GV); 921 Prefix = '@'; 922 } else { 923 Slot = Machine->getLocalSlot(V); 924 } 925 } else { 926 Slot = -1; 927 } 928 delete Machine; 929 } 930 931 if (Slot != -1) 932 Out << Prefix << Slot; 933 else 934 Out << "<badref>"; 935} 936 937/// WriteAsOperand - Write the name of the specified value out to the specified 938/// ostream. This can be useful when you just want to print int %reg126, not 939/// the whole instruction that generated it. 940/// 941void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType, 942 const Module *Context) { 943 raw_os_ostream OS(Out); 944 WriteAsOperand(OS, V, PrintType, Context); 945} 946 947void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType, 948 const Module *Context) { 949 std::map<const Type *, std::string> TypeNames; 950 if (Context == 0) Context = getModuleFromVal(V); 951 952 if (Context) 953 fillTypeNameTable(Context, TypeNames); 954 955 if (PrintType) 956 printTypeInt(Out, V->getType(), TypeNames); 957 958 WriteAsOperandInternal(Out, V, TypeNames, 0); 959} 960 961 962namespace { 963 964class AssemblyWriter { 965 raw_ostream &Out; 966 SlotTracker &Machine; 967 const Module *TheModule; 968 std::map<const Type *, std::string> TypeNames; 969 AssemblyAnnotationWriter *AnnotationWriter; 970public: 971 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M, 972 AssemblyAnnotationWriter *AAW) 973 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) { 974 975 // If the module has a symbol table, take all global types and stuff their 976 // names into the TypeNames map. 977 // 978 fillTypeNameTable(M, TypeNames); 979 } 980 981 void write(const Module *M) { printModule(M); } 982 983 void write(const GlobalValue *G) { 984 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) 985 printGlobal(GV); 986 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G)) 987 printAlias(GA); 988 else if (const Function *F = dyn_cast<Function>(G)) 989 printFunction(F); 990 else 991 assert(0 && "Unknown global"); 992 } 993 994 void write(const BasicBlock *BB) { printBasicBlock(BB); } 995 void write(const Instruction *I) { printInstruction(*I); } 996 void write(const Type *Ty) { printType(Ty); } 997 998 void writeOperand(const Value *Op, bool PrintType); 999 void writeParamOperand(const Value *Operand, ParameterAttributes Attrs); 1000 1001 const Module* getModule() { return TheModule; } 1002 1003private: 1004 void printModule(const Module *M); 1005 void printTypeSymbolTable(const TypeSymbolTable &ST); 1006 void printGlobal(const GlobalVariable *GV); 1007 void printAlias(const GlobalAlias *GV); 1008 void printFunction(const Function *F); 1009 void printArgument(const Argument *FA, ParameterAttributes Attrs); 1010 void printBasicBlock(const BasicBlock *BB); 1011 void printInstruction(const Instruction &I); 1012 1013 // printType - Go to extreme measures to attempt to print out a short, 1014 // symbolic version of a type name. 1015 // 1016 void printType(const Type *Ty) { 1017 printTypeInt(Out, Ty, TypeNames); 1018 } 1019 1020 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type 1021 // without considering any symbolic types that we may have equal to it. 1022 // 1023 void printTypeAtLeastOneLevel(const Type *Ty); 1024 1025 // printInfoComment - Print a little comment after the instruction indicating 1026 // which slot it occupies. 1027 void printInfoComment(const Value &V); 1028}; 1029} // end of llvm namespace 1030 1031/// printTypeAtLeastOneLevel - Print out one level of the possibly complex type 1032/// without considering any symbolic types that we may have equal to it. 1033/// 1034void AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) { 1035 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) { 1036 Out << "i" << utostr(ITy->getBitWidth()); 1037 return; 1038 } 1039 1040 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) { 1041 printType(FTy->getReturnType()); 1042 Out << " ("; 1043 for (FunctionType::param_iterator I = FTy->param_begin(), 1044 E = FTy->param_end(); I != E; ++I) { 1045 if (I != FTy->param_begin()) 1046 Out << ", "; 1047 printType(*I); 1048 } 1049 if (FTy->isVarArg()) { 1050 if (FTy->getNumParams()) Out << ", "; 1051 Out << "..."; 1052 } 1053 Out << ')'; 1054 return; 1055 } 1056 1057 if (const StructType *STy = dyn_cast<StructType>(Ty)) { 1058 if (STy->isPacked()) 1059 Out << '<'; 1060 Out << "{ "; 1061 for (StructType::element_iterator I = STy->element_begin(), 1062 E = STy->element_end(); I != E; ++I) { 1063 if (I != STy->element_begin()) 1064 Out << ", "; 1065 printType(*I); 1066 } 1067 Out << " }"; 1068 if (STy->isPacked()) 1069 Out << '>'; 1070 return; 1071 } 1072 1073 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) { 1074 printType(PTy->getElementType()); 1075 if (unsigned AddressSpace = PTy->getAddressSpace()) 1076 Out << " addrspace(" << AddressSpace << ")"; 1077 Out << '*'; 1078 return; 1079 } 1080 1081 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1082 Out << '[' << ATy->getNumElements() << " x "; 1083 printType(ATy->getElementType()); 1084 Out << ']'; 1085 return; 1086 } 1087 1088 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) { 1089 Out << '<' << PTy->getNumElements() << " x "; 1090 printType(PTy->getElementType()); 1091 Out << '>'; 1092 return; 1093 } 1094 1095 if (isa<OpaqueType>(Ty)) { 1096 Out << "opaque"; 1097 return; 1098 } 1099 1100 if (!Ty->isPrimitiveType()) 1101 Out << "<unknown derived type>"; 1102 printType(Ty); 1103} 1104 1105 1106void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) { 1107 if (Operand == 0) { 1108 Out << "<null operand!>"; 1109 } else { 1110 if (PrintType) { 1111 Out << ' '; 1112 printType(Operand->getType()); 1113 } 1114 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine); 1115 } 1116} 1117 1118void AssemblyWriter::writeParamOperand(const Value *Operand, 1119 ParameterAttributes Attrs) { 1120 if (Operand == 0) { 1121 Out << "<null operand!>"; 1122 } else { 1123 Out << ' '; 1124 // Print the type 1125 printType(Operand->getType()); 1126 // Print parameter attributes list 1127 if (Attrs != ParamAttr::None) 1128 Out << ' ' << ParamAttr::getAsString(Attrs); 1129 // Print the operand 1130 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine); 1131 } 1132} 1133 1134void AssemblyWriter::printModule(const Module *M) { 1135 if (!M->getModuleIdentifier().empty() && 1136 // Don't print the ID if it will start a new line (which would 1137 // require a comment char before it). 1138 M->getModuleIdentifier().find('\n') == std::string::npos) 1139 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 1140 1141 if (!M->getDataLayout().empty()) 1142 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n"; 1143 if (!M->getTargetTriple().empty()) 1144 Out << "target triple = \"" << M->getTargetTriple() << "\"\n"; 1145 1146 if (!M->getModuleInlineAsm().empty()) { 1147 // Split the string into lines, to make it easier to read the .ll file. 1148 std::string Asm = M->getModuleInlineAsm(); 1149 size_t CurPos = 0; 1150 size_t NewLine = Asm.find_first_of('\n', CurPos); 1151 while (NewLine != std::string::npos) { 1152 // We found a newline, print the portion of the asm string from the 1153 // last newline up to this newline. 1154 Out << "module asm \""; 1155 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine), 1156 Out); 1157 Out << "\"\n"; 1158 CurPos = NewLine+1; 1159 NewLine = Asm.find_first_of('\n', CurPos); 1160 } 1161 Out << "module asm \""; 1162 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out); 1163 Out << "\"\n"; 1164 } 1165 1166 // Loop over the dependent libraries and emit them. 1167 Module::lib_iterator LI = M->lib_begin(); 1168 Module::lib_iterator LE = M->lib_end(); 1169 if (LI != LE) { 1170 Out << "deplibs = [ "; 1171 while (LI != LE) { 1172 Out << '"' << *LI << '"'; 1173 ++LI; 1174 if (LI != LE) 1175 Out << ", "; 1176 } 1177 Out << " ]\n"; 1178 } 1179 1180 // Loop over the symbol table, emitting all named constants. 1181 printTypeSymbolTable(M->getTypeSymbolTable()); 1182 1183 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); 1184 I != E; ++I) 1185 printGlobal(I); 1186 1187 // Output all aliases. 1188 if (!M->alias_empty()) Out << "\n"; 1189 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end(); 1190 I != E; ++I) 1191 printAlias(I); 1192 1193 // Output all of the functions. 1194 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) 1195 printFunction(I); 1196} 1197 1198static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) { 1199 switch (LT) { 1200 case GlobalValue::InternalLinkage: Out << "internal "; break; 1201 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break; 1202 case GlobalValue::WeakLinkage: Out << "weak "; break; 1203 case GlobalValue::CommonLinkage: Out << "common "; break; 1204 case GlobalValue::AppendingLinkage: Out << "appending "; break; 1205 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break; 1206 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break; 1207 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break; 1208 case GlobalValue::ExternalLinkage: break; 1209 case GlobalValue::GhostLinkage: 1210 Out << "GhostLinkage not allowed in AsmWriter!\n"; 1211 abort(); 1212 } 1213} 1214 1215 1216static void PrintVisibility(GlobalValue::VisibilityTypes Vis, 1217 raw_ostream &Out) { 1218 switch (Vis) { 1219 default: assert(0 && "Invalid visibility style!"); 1220 case GlobalValue::DefaultVisibility: break; 1221 case GlobalValue::HiddenVisibility: Out << "hidden "; break; 1222 case GlobalValue::ProtectedVisibility: Out << "protected "; break; 1223 } 1224} 1225 1226void AssemblyWriter::printGlobal(const GlobalVariable *GV) { 1227 if (GV->hasName()) { 1228 PrintLLVMName(Out, GV); 1229 Out << " = "; 1230 } 1231 1232 if (!GV->hasInitializer() && GV->hasExternalLinkage()) 1233 Out << "external "; 1234 1235 PrintLinkage(GV->getLinkage(), Out); 1236 PrintVisibility(GV->getVisibility(), Out); 1237 1238 if (GV->isThreadLocal()) Out << "thread_local "; 1239 Out << (GV->isConstant() ? "constant " : "global "); 1240 printType(GV->getType()->getElementType()); 1241 1242 if (GV->hasInitializer()) 1243 writeOperand(GV->getInitializer(), false); 1244 1245 if (unsigned AddressSpace = GV->getType()->getAddressSpace()) 1246 Out << " addrspace(" << AddressSpace << ") "; 1247 1248 if (GV->hasSection()) 1249 Out << ", section \"" << GV->getSection() << '"'; 1250 if (GV->getAlignment()) 1251 Out << ", align " << GV->getAlignment(); 1252 1253 printInfoComment(*GV); 1254 Out << '\n'; 1255} 1256 1257void AssemblyWriter::printAlias(const GlobalAlias *GA) { 1258 // Don't crash when dumping partially built GA 1259 if (!GA->hasName()) 1260 Out << "<<nameless>> = "; 1261 else { 1262 PrintLLVMName(Out, GA); 1263 Out << " = "; 1264 } 1265 PrintVisibility(GA->getVisibility(), Out); 1266 1267 Out << "alias "; 1268 1269 PrintLinkage(GA->getLinkage(), Out); 1270 1271 const Constant *Aliasee = GA->getAliasee(); 1272 1273 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) { 1274 printType(GV->getType()); 1275 Out << ' '; 1276 PrintLLVMName(Out, GV); 1277 } else if (const Function *F = dyn_cast<Function>(Aliasee)) { 1278 printType(F->getFunctionType()); 1279 Out << "* "; 1280 1281 if (F->hasName()) 1282 PrintLLVMName(Out, F); 1283 else 1284 Out << "@\"\""; 1285 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) { 1286 printType(GA->getType()); 1287 Out << " "; 1288 PrintLLVMName(Out, GA); 1289 } else { 1290 const ConstantExpr *CE = 0; 1291 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) && 1292 (CE->getOpcode() == Instruction::BitCast)) { 1293 writeOperand(CE, false); 1294 } else 1295 assert(0 && "Unsupported aliasee"); 1296 } 1297 1298 printInfoComment(*GA); 1299 Out << '\n'; 1300} 1301 1302void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) { 1303 // Print the types. 1304 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end(); 1305 TI != TE; ++TI) { 1306 Out << '\t'; 1307 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix); 1308 Out << " = type "; 1309 1310 // Make sure we print out at least one level of the type structure, so 1311 // that we do not get %FILE = type %FILE 1312 // 1313 printTypeAtLeastOneLevel(TI->second); 1314 Out << '\n'; 1315 } 1316} 1317 1318/// printFunction - Print all aspects of a function. 1319/// 1320void AssemblyWriter::printFunction(const Function *F) { 1321 // Print out the return type and name. 1322 Out << '\n'; 1323 1324 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out); 1325 1326 if (F->isDeclaration()) 1327 Out << "declare "; 1328 else 1329 Out << "define "; 1330 1331 PrintLinkage(F->getLinkage(), Out); 1332 PrintVisibility(F->getVisibility(), Out); 1333 1334 // Print the calling convention. 1335 switch (F->getCallingConv()) { 1336 case CallingConv::C: break; // default 1337 case CallingConv::Fast: Out << "fastcc "; break; 1338 case CallingConv::Cold: Out << "coldcc "; break; 1339 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break; 1340 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 1341 case CallingConv::X86_SSECall: Out << "x86_ssecallcc "; break; 1342 default: Out << "cc" << F->getCallingConv() << " "; break; 1343 } 1344 1345 const FunctionType *FT = F->getFunctionType(); 1346 const PAListPtr &Attrs = F->getParamAttrs(); 1347 printType(F->getReturnType()); 1348 Out << ' '; 1349 if (F->hasName()) 1350 PrintLLVMName(Out, F); 1351 else 1352 Out << "@\"\""; 1353 Out << '('; 1354 Machine.incorporateFunction(F); 1355 1356 // Loop over the arguments, printing them... 1357 1358 unsigned Idx = 1; 1359 if (!F->isDeclaration()) { 1360 // If this isn't a declaration, print the argument names as well. 1361 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 1362 I != E; ++I) { 1363 // Insert commas as we go... the first arg doesn't get a comma 1364 if (I != F->arg_begin()) Out << ", "; 1365 printArgument(I, Attrs.getParamAttrs(Idx)); 1366 Idx++; 1367 } 1368 } else { 1369 // Otherwise, print the types from the function type. 1370 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1371 // Insert commas as we go... the first arg doesn't get a comma 1372 if (i) Out << ", "; 1373 1374 // Output type... 1375 printType(FT->getParamType(i)); 1376 1377 ParameterAttributes ArgAttrs = Attrs.getParamAttrs(i+1); 1378 if (ArgAttrs != ParamAttr::None) 1379 Out << ' ' << ParamAttr::getAsString(ArgAttrs); 1380 } 1381 } 1382 1383 // Finish printing arguments... 1384 if (FT->isVarArg()) { 1385 if (FT->getNumParams()) Out << ", "; 1386 Out << "..."; // Output varargs portion of signature! 1387 } 1388 Out << ')'; 1389 ParameterAttributes RetAttrs = Attrs.getParamAttrs(0); 1390 if (RetAttrs != ParamAttr::None) 1391 Out << ' ' << ParamAttr::getAsString(Attrs.getParamAttrs(0)); 1392 if (F->hasSection()) 1393 Out << " section \"" << F->getSection() << '"'; 1394 if (F->getAlignment()) 1395 Out << " align " << F->getAlignment(); 1396 if (F->hasGC()) 1397 Out << " gc \"" << F->getGC() << '"'; 1398 1399 if (F->isDeclaration()) { 1400 Out << "\n"; 1401 } else { 1402 Out << " {"; 1403 1404 // Output all of its basic blocks... for the function 1405 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I) 1406 printBasicBlock(I); 1407 1408 Out << "}\n"; 1409 } 1410 1411 Machine.purgeFunction(); 1412} 1413 1414/// printArgument - This member is called for every argument that is passed into 1415/// the function. Simply print it out 1416/// 1417void AssemblyWriter::printArgument(const Argument *Arg, 1418 ParameterAttributes Attrs) { 1419 // Output type... 1420 printType(Arg->getType()); 1421 1422 // Output parameter attributes list 1423 if (Attrs != ParamAttr::None) 1424 Out << ' ' << ParamAttr::getAsString(Attrs); 1425 1426 // Output name, if available... 1427 if (Arg->hasName()) { 1428 Out << ' '; 1429 PrintLLVMName(Out, Arg); 1430 } 1431} 1432 1433/// printBasicBlock - This member is called for each basic block in a method. 1434/// 1435void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { 1436 if (BB->hasName()) { // Print out the label if it exists... 1437 Out << "\n"; 1438 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix); 1439 Out << ':'; 1440 } else if (!BB->use_empty()) { // Don't print block # of no uses... 1441 Out << "\n; <label>:"; 1442 int Slot = Machine.getLocalSlot(BB); 1443 if (Slot != -1) 1444 Out << Slot; 1445 else 1446 Out << "<badref>"; 1447 } 1448 1449 if (BB->getParent() == 0) 1450 Out << "\t\t; Error: Block without parent!"; 1451 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block? 1452 // Output predecessors for the block... 1453 Out << "\t\t;"; 1454 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB); 1455 1456 if (PI == PE) { 1457 Out << " No predecessors!"; 1458 } else { 1459 Out << " preds ="; 1460 writeOperand(*PI, false); 1461 for (++PI; PI != PE; ++PI) { 1462 Out << ','; 1463 writeOperand(*PI, false); 1464 } 1465 } 1466 } 1467 1468 Out << "\n"; 1469 1470 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out); 1471 1472 // Output all of the instructions in the basic block... 1473 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) 1474 printInstruction(*I); 1475 1476 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out); 1477} 1478 1479 1480/// printInfoComment - Print a little comment after the instruction indicating 1481/// which slot it occupies. 1482/// 1483void AssemblyWriter::printInfoComment(const Value &V) { 1484 if (V.getType() != Type::VoidTy) { 1485 Out << "\t\t; <"; 1486 printType(V.getType()); 1487 Out << '>'; 1488 1489 if (!V.hasName()) { 1490 int SlotNum; 1491 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V)) 1492 SlotNum = Machine.getGlobalSlot(GV); 1493 else 1494 SlotNum = Machine.getLocalSlot(&V); 1495 if (SlotNum == -1) 1496 Out << ":<badref>"; 1497 else 1498 Out << ':' << SlotNum; // Print out the def slot taken. 1499 } 1500 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses 1501 } 1502} 1503 1504// This member is called for each Instruction in a function.. 1505void AssemblyWriter::printInstruction(const Instruction &I) { 1506 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out); 1507 1508 Out << '\t'; 1509 1510 // Print out name if it exists... 1511 if (I.hasName()) { 1512 PrintLLVMName(Out, &I); 1513 Out << " = "; 1514 } 1515 1516 // If this is a volatile load or store, print out the volatile marker. 1517 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) || 1518 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) { 1519 Out << "volatile "; 1520 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) { 1521 // If this is a call, check if it's a tail call. 1522 Out << "tail "; 1523 } 1524 1525 // Print out the opcode... 1526 Out << I.getOpcodeName(); 1527 1528 // Print out the compare instruction predicates 1529 if (const CmpInst *CI = dyn_cast<CmpInst>(&I)) 1530 Out << ' ' << getPredicateText(CI->getPredicate()); 1531 1532 // Print out the type of the operands... 1533 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0; 1534 1535 // Special case conditional branches to swizzle the condition out to the front 1536 if (isa<BranchInst>(I) && I.getNumOperands() > 1) { 1537 writeOperand(I.getOperand(2), true); 1538 Out << ','; 1539 writeOperand(Operand, true); 1540 Out << ','; 1541 writeOperand(I.getOperand(1), true); 1542 1543 } else if (isa<SwitchInst>(I)) { 1544 // Special case switch statement to get formatting nice and correct... 1545 writeOperand(Operand , true); 1546 Out << ','; 1547 writeOperand(I.getOperand(1), true); 1548 Out << " ["; 1549 1550 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) { 1551 Out << "\n\t\t"; 1552 writeOperand(I.getOperand(op ), true); 1553 Out << ','; 1554 writeOperand(I.getOperand(op+1), true); 1555 } 1556 Out << "\n\t]"; 1557 } else if (isa<PHINode>(I)) { 1558 Out << ' '; 1559 printType(I.getType()); 1560 Out << ' '; 1561 1562 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) { 1563 if (op) Out << ", "; 1564 Out << '['; 1565 writeOperand(I.getOperand(op ), false); Out << ','; 1566 writeOperand(I.getOperand(op+1), false); Out << " ]"; 1567 } 1568 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) { 1569 writeOperand(I.getOperand(0), true); 1570 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i) 1571 Out << ", " << *i; 1572 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) { 1573 writeOperand(I.getOperand(0), true); Out << ','; 1574 writeOperand(I.getOperand(1), true); 1575 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i) 1576 Out << ", " << *i; 1577 } else if (isa<ReturnInst>(I) && !Operand) { 1578 Out << " void"; 1579 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 1580 // Print the calling convention being used. 1581 switch (CI->getCallingConv()) { 1582 case CallingConv::C: break; // default 1583 case CallingConv::Fast: Out << " fastcc"; break; 1584 case CallingConv::Cold: Out << " coldcc"; break; 1585 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break; 1586 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break; 1587 case CallingConv::X86_SSECall: Out << " x86_ssecallcc"; break; 1588 default: Out << " cc" << CI->getCallingConv(); break; 1589 } 1590 1591 const PointerType *PTy = cast<PointerType>(Operand->getType()); 1592 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1593 const Type *RetTy = FTy->getReturnType(); 1594 const PAListPtr &PAL = CI->getParamAttrs(); 1595 1596 // If possible, print out the short form of the call instruction. We can 1597 // only do this if the first argument is a pointer to a nonvararg function, 1598 // and if the return type is not a pointer to a function. 1599 // 1600 if (!FTy->isVarArg() && 1601 (!isa<PointerType>(RetTy) || 1602 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) { 1603 Out << ' '; printType(RetTy); 1604 writeOperand(Operand, false); 1605 } else { 1606 writeOperand(Operand, true); 1607 } 1608 Out << '('; 1609 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) { 1610 if (op > 1) 1611 Out << ','; 1612 writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op)); 1613 } 1614 Out << " )"; 1615 if (PAL.getParamAttrs(0) != ParamAttr::None) 1616 Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0)); 1617 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 1618 const PointerType *PTy = cast<PointerType>(Operand->getType()); 1619 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1620 const Type *RetTy = FTy->getReturnType(); 1621 const PAListPtr &PAL = II->getParamAttrs(); 1622 1623 // Print the calling convention being used. 1624 switch (II->getCallingConv()) { 1625 case CallingConv::C: break; // default 1626 case CallingConv::Fast: Out << " fastcc"; break; 1627 case CallingConv::Cold: Out << " coldcc"; break; 1628 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break; 1629 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 1630 case CallingConv::X86_SSECall: Out << "x86_ssecallcc "; break; 1631 default: Out << " cc" << II->getCallingConv(); break; 1632 } 1633 1634 // If possible, print out the short form of the invoke instruction. We can 1635 // only do this if the first argument is a pointer to a nonvararg function, 1636 // and if the return type is not a pointer to a function. 1637 // 1638 if (!FTy->isVarArg() && 1639 (!isa<PointerType>(RetTy) || 1640 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) { 1641 Out << ' '; printType(RetTy); 1642 writeOperand(Operand, false); 1643 } else { 1644 writeOperand(Operand, true); 1645 } 1646 1647 Out << '('; 1648 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) { 1649 if (op > 3) 1650 Out << ','; 1651 writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op-2)); 1652 } 1653 1654 Out << " )"; 1655 if (PAL.getParamAttrs(0) != ParamAttr::None) 1656 Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0)); 1657 Out << "\n\t\t\tto"; 1658 writeOperand(II->getNormalDest(), true); 1659 Out << " unwind"; 1660 writeOperand(II->getUnwindDest(), true); 1661 1662 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) { 1663 Out << ' '; 1664 printType(AI->getType()->getElementType()); 1665 if (AI->isArrayAllocation()) { 1666 Out << ','; 1667 writeOperand(AI->getArraySize(), true); 1668 } 1669 if (AI->getAlignment()) { 1670 Out << ", align " << AI->getAlignment(); 1671 } 1672 } else if (isa<CastInst>(I)) { 1673 if (Operand) writeOperand(Operand, true); // Work with broken code 1674 Out << " to "; 1675 printType(I.getType()); 1676 } else if (isa<VAArgInst>(I)) { 1677 if (Operand) writeOperand(Operand, true); // Work with broken code 1678 Out << ", "; 1679 printType(I.getType()); 1680 } else if (Operand) { // Print the normal way... 1681 1682 // PrintAllTypes - Instructions who have operands of all the same type 1683 // omit the type from all but the first operand. If the instruction has 1684 // different type operands (for example br), then they are all printed. 1685 bool PrintAllTypes = false; 1686 const Type *TheType = Operand->getType(); 1687 1688 // Select, Store and ShuffleVector always print all types. 1689 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) 1690 || isa<ReturnInst>(I)) { 1691 PrintAllTypes = true; 1692 } else { 1693 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) { 1694 Operand = I.getOperand(i); 1695 if (Operand->getType() != TheType) { 1696 PrintAllTypes = true; // We have differing types! Print them all! 1697 break; 1698 } 1699 } 1700 } 1701 1702 if (!PrintAllTypes) { 1703 Out << ' '; 1704 printType(TheType); 1705 } 1706 1707 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) { 1708 if (i) Out << ','; 1709 writeOperand(I.getOperand(i), PrintAllTypes); 1710 } 1711 } 1712 1713 // Print post operand alignment for load/store 1714 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) { 1715 Out << ", align " << cast<LoadInst>(I).getAlignment(); 1716 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) { 1717 Out << ", align " << cast<StoreInst>(I).getAlignment(); 1718 } 1719 1720 printInfoComment(I); 1721 Out << '\n'; 1722} 1723 1724 1725//===----------------------------------------------------------------------===// 1726// External Interface declarations 1727//===----------------------------------------------------------------------===// 1728 1729void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 1730 raw_os_ostream OS(o); 1731 print(OS, AAW); 1732} 1733void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const { 1734 SlotTracker SlotTable(this); 1735 AssemblyWriter W(OS, SlotTable, this, AAW); 1736 W.write(this); 1737} 1738 1739void Type::print(std::ostream &o) const { 1740 raw_os_ostream OS(o); 1741 print(OS); 1742} 1743 1744void Type::print(raw_ostream &o) const { 1745 if (this == 0) 1746 o << "<null Type>"; 1747 else 1748 o << getDescription(); 1749} 1750 1751void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const { 1752 if (this == 0) { 1753 OS << "printing a <null> value\n"; 1754 return; 1755 } 1756 1757 if (const Instruction *I = dyn_cast<Instruction>(this)) { 1758 const Function *F = I->getParent() ? I->getParent()->getParent() : 0; 1759 SlotTracker SlotTable(F); 1760 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW); 1761 W.write(I); 1762 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) { 1763 SlotTracker SlotTable(BB->getParent()); 1764 AssemblyWriter W(OS, SlotTable, 1765 BB->getParent() ? BB->getParent()->getParent() : 0, AAW); 1766 W.write(BB); 1767 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) { 1768 SlotTracker SlotTable(GV->getParent()); 1769 AssemblyWriter W(OS, SlotTable, GV->getParent(), 0); 1770 W.write(GV); 1771 } else if (const Constant *C = dyn_cast<Constant>(this)) { 1772 OS << ' ' << C->getType()->getDescription() << ' '; 1773 std::map<const Type *, std::string> TypeTable; 1774 WriteConstantInt(OS, C, TypeTable, 0); 1775 } else if (const Argument *A = dyn_cast<Argument>(this)) { 1776 WriteAsOperand(OS, this, true, 1777 A->getParent() ? A->getParent()->getParent() : 0); 1778 } else if (isa<InlineAsm>(this)) { 1779 WriteAsOperand(OS, this, true, 0); 1780 } else { 1781 // FIXME: PseudoSourceValue breaks this! 1782 //assert(0 && "Unknown value to print out!"); 1783 } 1784} 1785 1786void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const { 1787 raw_os_ostream OS(O); 1788 print(OS, AAW); 1789} 1790 1791// Value::dump - allow easy printing of Values from the debugger. 1792// Located here because so much of the needed functionality is here. 1793void Value::dump() const { print(errs()); errs() << '\n'; errs().flush(); } 1794 1795// Type::dump - allow easy printing of Values from the debugger. 1796// Located here because so much of the needed functionality is here. 1797void Type::dump() const { print(errs()); errs() << '\n'; errs().flush(); } 1798 1799// Module::dump() - Allow printing from debugger 1800void Module::dump() const { print(errs(), 0); errs().flush(); } 1801 1802 1803