AsmWriter.cpp revision 1cde4af15712f6ccdb81ab540df800cda90d0d74
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/LLVMContext.h" 21#include "llvm/CallingConv.h" 22#include "llvm/Constants.h" 23#include "llvm/DerivedTypes.h" 24#include "llvm/InlineAsm.h" 25#include "llvm/IntrinsicInst.h" 26#include "llvm/Operator.h" 27#include "llvm/Module.h" 28#include "llvm/ValueSymbolTable.h" 29#include "llvm/TypeSymbolTable.h" 30#include "llvm/ADT/DenseSet.h" 31#include "llvm/ADT/SmallString.h" 32#include "llvm/ADT/StringExtras.h" 33#include "llvm/ADT/STLExtras.h" 34#include "llvm/Support/CFG.h" 35#include "llvm/Support/Debug.h" 36#include "llvm/Support/Dwarf.h" 37#include "llvm/Support/ErrorHandling.h" 38#include "llvm/Support/MathExtras.h" 39#include "llvm/Support/FormattedStream.h" 40#include <algorithm> 41#include <cctype> 42#include <map> 43using namespace llvm; 44 45// Make virtual table appear in this compilation unit. 46AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {} 47 48//===----------------------------------------------------------------------===// 49// Helper Functions 50//===----------------------------------------------------------------------===// 51 52static const Module *getModuleFromVal(const Value *V) { 53 if (const Argument *MA = dyn_cast<Argument>(V)) 54 return MA->getParent() ? MA->getParent()->getParent() : 0; 55 56 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 57 return BB->getParent() ? BB->getParent()->getParent() : 0; 58 59 if (const Instruction *I = dyn_cast<Instruction>(V)) { 60 const Function *M = I->getParent() ? I->getParent()->getParent() : 0; 61 return M ? M->getParent() : 0; 62 } 63 64 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 65 return GV->getParent(); 66 if (const NamedMDNode *NMD = dyn_cast<NamedMDNode>(V)) 67 return NMD->getParent(); 68 return 0; 69} 70 71// PrintEscapedString - Print each character of the specified string, escaping 72// it if it is not printable or if it is an escape char. 73static void PrintEscapedString(const StringRef &Name, 74 raw_ostream &Out) { 75 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 76 unsigned char C = Name[i]; 77 if (isprint(C) && C != '\\' && C != '"') 78 Out << C; 79 else 80 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F); 81 } 82} 83 84enum PrefixType { 85 GlobalPrefix, 86 LabelPrefix, 87 LocalPrefix, 88 NoPrefix 89}; 90 91/// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either 92/// prefixed with % (if the string only contains simple characters) or is 93/// surrounded with ""'s (if it has special chars in it). Print it out. 94static void PrintLLVMName(raw_ostream &OS, const StringRef &Name, 95 PrefixType Prefix) { 96 assert(Name.data() && "Cannot get empty name!"); 97 switch (Prefix) { 98 default: llvm_unreachable("Bad prefix!"); 99 case NoPrefix: break; 100 case GlobalPrefix: OS << '@'; break; 101 case LabelPrefix: break; 102 case LocalPrefix: OS << '%'; break; 103 } 104 105 // Scan the name to see if it needs quotes first. 106 bool NeedsQuotes = isdigit(Name[0]); 107 if (!NeedsQuotes) { 108 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 109 char C = Name[i]; 110 if (!isalnum(C) && C != '-' && C != '.' && C != '_') { 111 NeedsQuotes = true; 112 break; 113 } 114 } 115 } 116 117 // If we didn't need any quotes, just write out the name in one blast. 118 if (!NeedsQuotes) { 119 OS << Name; 120 return; 121 } 122 123 // Okay, we need quotes. Output the quotes and escape any scary characters as 124 // needed. 125 OS << '"'; 126 PrintEscapedString(Name, OS); 127 OS << '"'; 128} 129 130/// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either 131/// prefixed with % (if the string only contains simple characters) or is 132/// surrounded with ""'s (if it has special chars in it). Print it out. 133static void PrintLLVMName(raw_ostream &OS, const Value *V) { 134 PrintLLVMName(OS, V->getName(), 135 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix); 136} 137 138//===----------------------------------------------------------------------===// 139// TypePrinting Class: Type printing machinery 140//===----------------------------------------------------------------------===// 141 142static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) { 143 return *static_cast<DenseMap<const Type *, std::string>*>(M); 144} 145 146void TypePrinting::clear() { 147 getTypeNamesMap(TypeNames).clear(); 148} 149 150bool TypePrinting::hasTypeName(const Type *Ty) const { 151 return getTypeNamesMap(TypeNames).count(Ty); 152} 153 154void TypePrinting::addTypeName(const Type *Ty, const std::string &N) { 155 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N)); 156} 157 158 159TypePrinting::TypePrinting() { 160 TypeNames = new DenseMap<const Type *, std::string>(); 161} 162 163TypePrinting::~TypePrinting() { 164 delete &getTypeNamesMap(TypeNames); 165} 166 167/// CalcTypeName - Write the specified type to the specified raw_ostream, making 168/// use of type names or up references to shorten the type name where possible. 169void TypePrinting::CalcTypeName(const Type *Ty, 170 SmallVectorImpl<const Type *> &TypeStack, 171 raw_ostream &OS, bool IgnoreTopLevelName) { 172 // Check to see if the type is named. 173 if (!IgnoreTopLevelName) { 174 DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames); 175 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty); 176 if (I != TM.end()) { 177 OS << I->second; 178 return; 179 } 180 } 181 182 // Check to see if the Type is already on the stack... 183 unsigned Slot = 0, CurSize = TypeStack.size(); 184 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type 185 186 // This is another base case for the recursion. In this case, we know 187 // that we have looped back to a type that we have previously visited. 188 // Generate the appropriate upreference to handle this. 189 if (Slot < CurSize) { 190 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference 191 return; 192 } 193 194 TypeStack.push_back(Ty); // Recursive case: Add us to the stack.. 195 196 switch (Ty->getTypeID()) { 197 case Type::VoidTyID: OS << "void"; break; 198 case Type::FloatTyID: OS << "float"; break; 199 case Type::DoubleTyID: OS << "double"; break; 200 case Type::X86_FP80TyID: OS << "x86_fp80"; break; 201 case Type::FP128TyID: OS << "fp128"; break; 202 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break; 203 case Type::LabelTyID: OS << "label"; break; 204 case Type::MetadataTyID: OS << "metadata"; break; 205 case Type::IntegerTyID: 206 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth(); 207 break; 208 209 case Type::FunctionTyID: { 210 const FunctionType *FTy = cast<FunctionType>(Ty); 211 CalcTypeName(FTy->getReturnType(), TypeStack, OS); 212 OS << " ("; 213 for (FunctionType::param_iterator I = FTy->param_begin(), 214 E = FTy->param_end(); I != E; ++I) { 215 if (I != FTy->param_begin()) 216 OS << ", "; 217 CalcTypeName(*I, TypeStack, OS); 218 } 219 if (FTy->isVarArg()) { 220 if (FTy->getNumParams()) OS << ", "; 221 OS << "..."; 222 } 223 OS << ')'; 224 break; 225 } 226 case Type::StructTyID: { 227 const StructType *STy = cast<StructType>(Ty); 228 if (STy->isPacked()) 229 OS << '<'; 230 OS << "{ "; 231 for (StructType::element_iterator I = STy->element_begin(), 232 E = STy->element_end(); I != E; ++I) { 233 CalcTypeName(*I, TypeStack, OS); 234 if (next(I) != STy->element_end()) 235 OS << ','; 236 OS << ' '; 237 } 238 OS << '}'; 239 if (STy->isPacked()) 240 OS << '>'; 241 break; 242 } 243 case Type::UnionTyID: { 244 const UnionType *UTy = cast<UnionType>(Ty); 245 OS << "union { "; 246 for (StructType::element_iterator I = UTy->element_begin(), 247 E = UTy->element_end(); I != E; ++I) { 248 CalcTypeName(*I, TypeStack, OS); 249 if (next(I) != UTy->element_end()) 250 OS << ','; 251 OS << ' '; 252 } 253 OS << '}'; 254 break; 255 } 256 case Type::PointerTyID: { 257 const PointerType *PTy = cast<PointerType>(Ty); 258 CalcTypeName(PTy->getElementType(), TypeStack, OS); 259 if (unsigned AddressSpace = PTy->getAddressSpace()) 260 OS << " addrspace(" << AddressSpace << ')'; 261 OS << '*'; 262 break; 263 } 264 case Type::ArrayTyID: { 265 const ArrayType *ATy = cast<ArrayType>(Ty); 266 OS << '[' << ATy->getNumElements() << " x "; 267 CalcTypeName(ATy->getElementType(), TypeStack, OS); 268 OS << ']'; 269 break; 270 } 271 case Type::VectorTyID: { 272 const VectorType *PTy = cast<VectorType>(Ty); 273 OS << "<" << PTy->getNumElements() << " x "; 274 CalcTypeName(PTy->getElementType(), TypeStack, OS); 275 OS << '>'; 276 break; 277 } 278 case Type::OpaqueTyID: 279 OS << "opaque"; 280 break; 281 default: 282 OS << "<unrecognized-type>"; 283 break; 284 } 285 286 TypeStack.pop_back(); // Remove self from stack. 287} 288 289/// printTypeInt - The internal guts of printing out a type that has a 290/// potentially named portion. 291/// 292void TypePrinting::print(const Type *Ty, raw_ostream &OS, 293 bool IgnoreTopLevelName) { 294 // Check to see if the type is named. 295 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames); 296 if (!IgnoreTopLevelName) { 297 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty); 298 if (I != TM.end()) { 299 OS << I->second; 300 return; 301 } 302 } 303 304 // Otherwise we have a type that has not been named but is a derived type. 305 // Carefully recurse the type hierarchy to print out any contained symbolic 306 // names. 307 SmallVector<const Type *, 16> TypeStack; 308 std::string TypeName; 309 310 raw_string_ostream TypeOS(TypeName); 311 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName); 312 OS << TypeOS.str(); 313 314 // Cache type name for later use. 315 if (!IgnoreTopLevelName) 316 TM.insert(std::make_pair(Ty, TypeOS.str())); 317} 318 319namespace { 320 class TypeFinder { 321 // To avoid walking constant expressions multiple times and other IR 322 // objects, we keep several helper maps. 323 DenseSet<const Value*> VisitedConstants; 324 DenseSet<const Type*> VisitedTypes; 325 326 TypePrinting &TP; 327 std::vector<const Type*> &NumberedTypes; 328 public: 329 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes) 330 : TP(tp), NumberedTypes(numberedTypes) {} 331 332 void Run(const Module &M) { 333 // Get types from the type symbol table. This gets opaque types referened 334 // only through derived named types. 335 const TypeSymbolTable &ST = M.getTypeSymbolTable(); 336 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end(); 337 TI != E; ++TI) 338 IncorporateType(TI->second); 339 340 // Get types from global variables. 341 for (Module::const_global_iterator I = M.global_begin(), 342 E = M.global_end(); I != E; ++I) { 343 IncorporateType(I->getType()); 344 if (I->hasInitializer()) 345 IncorporateValue(I->getInitializer()); 346 } 347 348 // Get types from aliases. 349 for (Module::const_alias_iterator I = M.alias_begin(), 350 E = M.alias_end(); I != E; ++I) { 351 IncorporateType(I->getType()); 352 IncorporateValue(I->getAliasee()); 353 } 354 355 // Get types from functions. 356 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) { 357 IncorporateType(FI->getType()); 358 359 for (Function::const_iterator BB = FI->begin(), E = FI->end(); 360 BB != E;++BB) 361 for (BasicBlock::const_iterator II = BB->begin(), 362 E = BB->end(); II != E; ++II) { 363 const Instruction &I = *II; 364 // Incorporate the type of the instruction and all its operands. 365 IncorporateType(I.getType()); 366 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end(); 367 OI != OE; ++OI) 368 IncorporateValue(*OI); 369 } 370 } 371 } 372 373 private: 374 void IncorporateType(const Type *Ty) { 375 // Check to see if we're already visited this type. 376 if (!VisitedTypes.insert(Ty).second) 377 return; 378 379 // If this is a structure or opaque type, add a name for the type. 380 if (((Ty->isStructTy() && cast<StructType>(Ty)->getNumElements()) 381 || Ty->isOpaqueTy()) && !TP.hasTypeName(Ty)) { 382 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size()))); 383 NumberedTypes.push_back(Ty); 384 } 385 386 // Recursively walk all contained types. 387 for (Type::subtype_iterator I = Ty->subtype_begin(), 388 E = Ty->subtype_end(); I != E; ++I) 389 IncorporateType(*I); 390 } 391 392 /// IncorporateValue - This method is used to walk operand lists finding 393 /// types hiding in constant expressions and other operands that won't be 394 /// walked in other ways. GlobalValues, basic blocks, instructions, and 395 /// inst operands are all explicitly enumerated. 396 void IncorporateValue(const Value *V) { 397 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return; 398 399 // Already visited? 400 if (!VisitedConstants.insert(V).second) 401 return; 402 403 // Check this type. 404 IncorporateType(V->getType()); 405 406 // Look in operands for types. 407 const Constant *C = cast<Constant>(V); 408 for (Constant::const_op_iterator I = C->op_begin(), 409 E = C->op_end(); I != E;++I) 410 IncorporateValue(*I); 411 } 412 }; 413} // end anonymous namespace 414 415 416/// AddModuleTypesToPrinter - Add all of the symbolic type names for types in 417/// the specified module to the TypePrinter and all numbered types to it and the 418/// NumberedTypes table. 419static void AddModuleTypesToPrinter(TypePrinting &TP, 420 std::vector<const Type*> &NumberedTypes, 421 const Module *M) { 422 if (M == 0) return; 423 424 // If the module has a symbol table, take all global types and stuff their 425 // names into the TypeNames map. 426 const TypeSymbolTable &ST = M->getTypeSymbolTable(); 427 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end(); 428 TI != E; ++TI) { 429 const Type *Ty = cast<Type>(TI->second); 430 431 // As a heuristic, don't insert pointer to primitive types, because 432 // they are used too often to have a single useful name. 433 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) { 434 const Type *PETy = PTy->getElementType(); 435 if ((PETy->isPrimitiveType() || PETy->isIntegerTy()) && 436 !PETy->isOpaqueTy()) 437 continue; 438 } 439 440 // Likewise don't insert primitives either. 441 if (Ty->isIntegerTy() || Ty->isPrimitiveType()) 442 continue; 443 444 // Get the name as a string and insert it into TypeNames. 445 std::string NameStr; 446 raw_string_ostream NameROS(NameStr); 447 formatted_raw_ostream NameOS(NameROS); 448 PrintLLVMName(NameOS, TI->first, LocalPrefix); 449 NameOS.flush(); 450 TP.addTypeName(Ty, NameStr); 451 } 452 453 // Walk the entire module to find references to unnamed structure and opaque 454 // types. This is required for correctness by opaque types (because multiple 455 // uses of an unnamed opaque type needs to be referred to by the same ID) and 456 // it shrinks complex recursive structure types substantially in some cases. 457 TypeFinder(TP, NumberedTypes).Run(*M); 458} 459 460 461/// WriteTypeSymbolic - This attempts to write the specified type as a symbolic 462/// type, iff there is an entry in the modules symbol table for the specified 463/// type or one of it's component types. 464/// 465void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) { 466 TypePrinting Printer; 467 std::vector<const Type*> NumberedTypes; 468 AddModuleTypesToPrinter(Printer, NumberedTypes, M); 469 Printer.print(Ty, OS); 470} 471 472//===----------------------------------------------------------------------===// 473// SlotTracker Class: Enumerate slot numbers for unnamed values 474//===----------------------------------------------------------------------===// 475 476namespace { 477 478/// This class provides computation of slot numbers for LLVM Assembly writing. 479/// 480class SlotTracker { 481public: 482 /// ValueMap - A mapping of Values to slot numbers. 483 typedef DenseMap<const Value*, unsigned> ValueMap; 484 485private: 486 /// TheModule - The module for which we are holding slot numbers. 487 const Module* TheModule; 488 489 /// TheFunction - The function for which we are holding slot numbers. 490 const Function* TheFunction; 491 bool FunctionProcessed; 492 493 /// mMap - The TypePlanes map for the module level data. 494 ValueMap mMap; 495 unsigned mNext; 496 497 /// fMap - The TypePlanes map for the function level data. 498 ValueMap fMap; 499 unsigned fNext; 500 501 /// mdnMap - Map for MDNodes. 502 DenseMap<const MDNode*, unsigned> mdnMap; 503 unsigned mdnNext; 504public: 505 /// Construct from a module 506 explicit SlotTracker(const Module *M); 507 /// Construct from a function, starting out in incorp state. 508 explicit SlotTracker(const Function *F); 509 510 /// Return the slot number of the specified value in it's type 511 /// plane. If something is not in the SlotTracker, return -1. 512 int getLocalSlot(const Value *V); 513 int getGlobalSlot(const GlobalValue *V); 514 int getMetadataSlot(const MDNode *N); 515 516 /// If you'd like to deal with a function instead of just a module, use 517 /// this method to get its data into the SlotTracker. 518 void incorporateFunction(const Function *F) { 519 TheFunction = F; 520 FunctionProcessed = false; 521 } 522 523 /// After calling incorporateFunction, use this method to remove the 524 /// most recently incorporated function from the SlotTracker. This 525 /// will reset the state of the machine back to just the module contents. 526 void purgeFunction(); 527 528 /// MDNode map iterators. 529 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator; 530 mdn_iterator mdn_begin() { return mdnMap.begin(); } 531 mdn_iterator mdn_end() { return mdnMap.end(); } 532 unsigned mdn_size() const { return mdnMap.size(); } 533 bool mdn_empty() const { return mdnMap.empty(); } 534 535 /// This function does the actual initialization. 536 inline void initialize(); 537 538 // Implementation Details 539private: 540 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 541 void CreateModuleSlot(const GlobalValue *V); 542 543 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table. 544 void CreateMetadataSlot(const MDNode *N); 545 546 /// CreateFunctionSlot - Insert the specified Value* into the slot table. 547 void CreateFunctionSlot(const Value *V); 548 549 /// Add all of the module level global variables (and their initializers) 550 /// and function declarations, but not the contents of those functions. 551 void processModule(); 552 553 /// Add all of the functions arguments, basic blocks, and instructions. 554 void processFunction(); 555 556 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT 557 void operator=(const SlotTracker &); // DO NOT IMPLEMENT 558}; 559 560} // end anonymous namespace 561 562 563static SlotTracker *createSlotTracker(const Value *V) { 564 if (const Argument *FA = dyn_cast<Argument>(V)) 565 return new SlotTracker(FA->getParent()); 566 567 if (const Instruction *I = dyn_cast<Instruction>(V)) 568 return new SlotTracker(I->getParent()->getParent()); 569 570 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 571 return new SlotTracker(BB->getParent()); 572 573 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) 574 return new SlotTracker(GV->getParent()); 575 576 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 577 return new SlotTracker(GA->getParent()); 578 579 if (const Function *Func = dyn_cast<Function>(V)) 580 return new SlotTracker(Func); 581 582 if (isa<MDNode>(V)) 583 return new SlotTracker((Function *)0); 584 585 return 0; 586} 587 588#if 0 589#define ST_DEBUG(X) dbgs() << X 590#else 591#define ST_DEBUG(X) 592#endif 593 594// Module level constructor. Causes the contents of the Module (sans functions) 595// to be added to the slot table. 596SlotTracker::SlotTracker(const Module *M) 597 : TheModule(M), TheFunction(0), FunctionProcessed(false), 598 mNext(0), fNext(0), mdnNext(0) { 599} 600 601// Function level constructor. Causes the contents of the Module and the one 602// function provided to be added to the slot table. 603SlotTracker::SlotTracker(const Function *F) 604 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false), 605 mNext(0), fNext(0), mdnNext(0) { 606} 607 608inline void SlotTracker::initialize() { 609 if (TheModule) { 610 processModule(); 611 TheModule = 0; ///< Prevent re-processing next time we're called. 612 } 613 614 if (TheFunction && !FunctionProcessed) 615 processFunction(); 616} 617 618// Iterate through all the global variables, functions, and global 619// variable initializers and create slots for them. 620void SlotTracker::processModule() { 621 ST_DEBUG("begin processModule!\n"); 622 623 // Add all of the unnamed global variables to the value table. 624 for (Module::const_global_iterator I = TheModule->global_begin(), 625 E = TheModule->global_end(); I != E; ++I) { 626 if (!I->hasName()) 627 CreateModuleSlot(I); 628 } 629 630 // Add metadata used by named metadata. 631 for (Module::const_named_metadata_iterator 632 I = TheModule->named_metadata_begin(), 633 E = TheModule->named_metadata_end(); I != E; ++I) { 634 const NamedMDNode *NMD = I; 635 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 636 if (MDNode *MD = NMD->getOperand(i)) 637 CreateMetadataSlot(MD); 638 } 639 } 640 641 // Add all the unnamed functions to the table. 642 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 643 I != E; ++I) 644 if (!I->hasName()) 645 CreateModuleSlot(I); 646 647 ST_DEBUG("end processModule!\n"); 648} 649 650// Process the arguments, basic blocks, and instructions of a function. 651void SlotTracker::processFunction() { 652 ST_DEBUG("begin processFunction!\n"); 653 fNext = 0; 654 655 // Add all the function arguments with no names. 656 for(Function::const_arg_iterator AI = TheFunction->arg_begin(), 657 AE = TheFunction->arg_end(); AI != AE; ++AI) 658 if (!AI->hasName()) 659 CreateFunctionSlot(AI); 660 661 ST_DEBUG("Inserting Instructions:\n"); 662 663 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst; 664 665 // Add all of the basic blocks and instructions with no names. 666 for (Function::const_iterator BB = TheFunction->begin(), 667 E = TheFunction->end(); BB != E; ++BB) { 668 if (!BB->hasName()) 669 CreateFunctionSlot(BB); 670 671 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; 672 ++I) { 673 if (!I->getType()->isVoidTy() && !I->hasName()) 674 CreateFunctionSlot(I); 675 676 // Intrinsics can directly use metadata. 677 if (isa<IntrinsicInst>(I)) 678 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 679 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i))) 680 CreateMetadataSlot(N); 681 682 // Process metadata attached with this instruction. 683 I->getAllMetadata(MDForInst); 684 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i) 685 CreateMetadataSlot(MDForInst[i].second); 686 MDForInst.clear(); 687 } 688 } 689 690 FunctionProcessed = true; 691 692 ST_DEBUG("end processFunction!\n"); 693} 694 695/// Clean up after incorporating a function. This is the only way to get out of 696/// the function incorporation state that affects get*Slot/Create*Slot. Function 697/// incorporation state is indicated by TheFunction != 0. 698void SlotTracker::purgeFunction() { 699 ST_DEBUG("begin purgeFunction!\n"); 700 fMap.clear(); // Simply discard the function level map 701 TheFunction = 0; 702 FunctionProcessed = false; 703 ST_DEBUG("end purgeFunction!\n"); 704} 705 706/// getGlobalSlot - Get the slot number of a global value. 707int SlotTracker::getGlobalSlot(const GlobalValue *V) { 708 // Check for uninitialized state and do lazy initialization. 709 initialize(); 710 711 // Find the type plane in the module map 712 ValueMap::iterator MI = mMap.find(V); 713 return MI == mMap.end() ? -1 : (int)MI->second; 714} 715 716/// getMetadataSlot - Get the slot number of a MDNode. 717int SlotTracker::getMetadataSlot(const MDNode *N) { 718 // Check for uninitialized state and do lazy initialization. 719 initialize(); 720 721 // Find the type plane in the module map 722 mdn_iterator MI = mdnMap.find(N); 723 return MI == mdnMap.end() ? -1 : (int)MI->second; 724} 725 726 727/// getLocalSlot - Get the slot number for a value that is local to a function. 728int SlotTracker::getLocalSlot(const Value *V) { 729 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!"); 730 731 // Check for uninitialized state and do lazy initialization. 732 initialize(); 733 734 ValueMap::iterator FI = fMap.find(V); 735 return FI == fMap.end() ? -1 : (int)FI->second; 736} 737 738 739/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 740void SlotTracker::CreateModuleSlot(const GlobalValue *V) { 741 assert(V && "Can't insert a null Value into SlotTracker!"); 742 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!"); 743 assert(!V->hasName() && "Doesn't need a slot!"); 744 745 unsigned DestSlot = mNext++; 746 mMap[V] = DestSlot; 747 748 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 749 DestSlot << " ["); 750 // G = Global, F = Function, A = Alias, o = other 751 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' : 752 (isa<Function>(V) ? 'F' : 753 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n"); 754} 755 756/// CreateSlot - Create a new slot for the specified value if it has no name. 757void SlotTracker::CreateFunctionSlot(const Value *V) { 758 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!"); 759 760 unsigned DestSlot = fNext++; 761 fMap[V] = DestSlot; 762 763 // G = Global, F = Function, o = other 764 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 765 DestSlot << " [o]\n"); 766} 767 768/// CreateModuleSlot - Insert the specified MDNode* into the slot table. 769void SlotTracker::CreateMetadataSlot(const MDNode *N) { 770 assert(N && "Can't insert a null Value into SlotTracker!"); 771 772 // Don't insert if N is a function-local metadata, these are always printed 773 // inline. 774 if (N->isFunctionLocal()) 775 return; 776 777 mdn_iterator I = mdnMap.find(N); 778 if (I != mdnMap.end()) 779 return; 780 781 unsigned DestSlot = mdnNext++; 782 mdnMap[N] = DestSlot; 783 784 // Recursively add any MDNodes referenced by operands. 785 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 786 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i))) 787 CreateMetadataSlot(Op); 788} 789 790//===----------------------------------------------------------------------===// 791// AsmWriter Implementation 792//===----------------------------------------------------------------------===// 793 794static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 795 TypePrinting *TypePrinter, 796 SlotTracker *Machine); 797 798 799 800static const char *getPredicateText(unsigned predicate) { 801 const char * pred = "unknown"; 802 switch (predicate) { 803 case FCmpInst::FCMP_FALSE: pred = "false"; break; 804 case FCmpInst::FCMP_OEQ: pred = "oeq"; break; 805 case FCmpInst::FCMP_OGT: pred = "ogt"; break; 806 case FCmpInst::FCMP_OGE: pred = "oge"; break; 807 case FCmpInst::FCMP_OLT: pred = "olt"; break; 808 case FCmpInst::FCMP_OLE: pred = "ole"; break; 809 case FCmpInst::FCMP_ONE: pred = "one"; break; 810 case FCmpInst::FCMP_ORD: pred = "ord"; break; 811 case FCmpInst::FCMP_UNO: pred = "uno"; break; 812 case FCmpInst::FCMP_UEQ: pred = "ueq"; break; 813 case FCmpInst::FCMP_UGT: pred = "ugt"; break; 814 case FCmpInst::FCMP_UGE: pred = "uge"; break; 815 case FCmpInst::FCMP_ULT: pred = "ult"; break; 816 case FCmpInst::FCMP_ULE: pred = "ule"; break; 817 case FCmpInst::FCMP_UNE: pred = "une"; break; 818 case FCmpInst::FCMP_TRUE: pred = "true"; break; 819 case ICmpInst::ICMP_EQ: pred = "eq"; break; 820 case ICmpInst::ICMP_NE: pred = "ne"; break; 821 case ICmpInst::ICMP_SGT: pred = "sgt"; break; 822 case ICmpInst::ICMP_SGE: pred = "sge"; break; 823 case ICmpInst::ICMP_SLT: pred = "slt"; break; 824 case ICmpInst::ICMP_SLE: pred = "sle"; break; 825 case ICmpInst::ICMP_UGT: pred = "ugt"; break; 826 case ICmpInst::ICMP_UGE: pred = "uge"; break; 827 case ICmpInst::ICMP_ULT: pred = "ult"; break; 828 case ICmpInst::ICMP_ULE: pred = "ule"; break; 829 } 830 return pred; 831} 832 833 834static void WriteOptimizationInfo(raw_ostream &Out, const User *U) { 835 if (const OverflowingBinaryOperator *OBO = 836 dyn_cast<OverflowingBinaryOperator>(U)) { 837 if (OBO->hasNoUnsignedWrap()) 838 Out << " nuw"; 839 if (OBO->hasNoSignedWrap()) 840 Out << " nsw"; 841 } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) { 842 if (Div->isExact()) 843 Out << " exact"; 844 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) { 845 if (GEP->isInBounds()) 846 Out << " inbounds"; 847 } 848} 849 850static void WriteConstantInt(raw_ostream &Out, const Constant *CV, 851 TypePrinting &TypePrinter, SlotTracker *Machine) { 852 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 853 if (CI->getType()->isIntegerTy(1)) { 854 Out << (CI->getZExtValue() ? "true" : "false"); 855 return; 856 } 857 Out << CI->getValue(); 858 return; 859 } 860 861 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 862 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble || 863 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) { 864 // We would like to output the FP constant value in exponential notation, 865 // but we cannot do this if doing so will lose precision. Check here to 866 // make sure that we only output it in exponential format if we can parse 867 // the value back and get the same value. 868 // 869 bool ignored; 870 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble; 871 double Val = isDouble ? CFP->getValueAPF().convertToDouble() : 872 CFP->getValueAPF().convertToFloat(); 873 SmallString<128> StrVal; 874 raw_svector_ostream(StrVal) << Val; 875 876 // Check to make sure that the stringized number is not some string like 877 // "Inf" or NaN, that atof will accept, but the lexer will not. Check 878 // that the string matches the "[-+]?[0-9]" regex. 879 // 880 if ((StrVal[0] >= '0' && StrVal[0] <= '9') || 881 ((StrVal[0] == '-' || StrVal[0] == '+') && 882 (StrVal[1] >= '0' && StrVal[1] <= '9'))) { 883 // Reparse stringized version! 884 if (atof(StrVal.c_str()) == Val) { 885 Out << StrVal.str(); 886 return; 887 } 888 } 889 // Otherwise we could not reparse it to exactly the same value, so we must 890 // output the string in hexadecimal format! Note that loading and storing 891 // floating point types changes the bits of NaNs on some hosts, notably 892 // x86, so we must not use these types. 893 assert(sizeof(double) == sizeof(uint64_t) && 894 "assuming that double is 64 bits!"); 895 char Buffer[40]; 896 APFloat apf = CFP->getValueAPF(); 897 // Floats are represented in ASCII IR as double, convert. 898 if (!isDouble) 899 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 900 &ignored); 901 Out << "0x" << 902 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()), 903 Buffer+40); 904 return; 905 } 906 907 // Some form of long double. These appear as a magic letter identifying 908 // the type, then a fixed number of hex digits. 909 Out << "0x"; 910 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) { 911 Out << 'K'; 912 // api needed to prevent premature destruction 913 APInt api = CFP->getValueAPF().bitcastToAPInt(); 914 const uint64_t* p = api.getRawData(); 915 uint64_t word = p[1]; 916 int shiftcount=12; 917 int width = api.getBitWidth(); 918 for (int j=0; j<width; j+=4, shiftcount-=4) { 919 unsigned int nibble = (word>>shiftcount) & 15; 920 if (nibble < 10) 921 Out << (unsigned char)(nibble + '0'); 922 else 923 Out << (unsigned char)(nibble - 10 + 'A'); 924 if (shiftcount == 0 && j+4 < width) { 925 word = *p; 926 shiftcount = 64; 927 if (width-j-4 < 64) 928 shiftcount = width-j-4; 929 } 930 } 931 return; 932 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) 933 Out << 'L'; 934 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) 935 Out << 'M'; 936 else 937 llvm_unreachable("Unsupported floating point type"); 938 // api needed to prevent premature destruction 939 APInt api = CFP->getValueAPF().bitcastToAPInt(); 940 const uint64_t* p = api.getRawData(); 941 uint64_t word = *p; 942 int shiftcount=60; 943 int width = api.getBitWidth(); 944 for (int j=0; j<width; j+=4, shiftcount-=4) { 945 unsigned int nibble = (word>>shiftcount) & 15; 946 if (nibble < 10) 947 Out << (unsigned char)(nibble + '0'); 948 else 949 Out << (unsigned char)(nibble - 10 + 'A'); 950 if (shiftcount == 0 && j+4 < width) { 951 word = *(++p); 952 shiftcount = 64; 953 if (width-j-4 < 64) 954 shiftcount = width-j-4; 955 } 956 } 957 return; 958 } 959 960 if (isa<ConstantAggregateZero>(CV)) { 961 Out << "zeroinitializer"; 962 return; 963 } 964 965 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) { 966 Out << "blockaddress("; 967 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine); 968 Out << ", "; 969 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine); 970 Out << ")"; 971 return; 972 } 973 974 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) { 975 // As a special case, print the array as a string if it is an array of 976 // i8 with ConstantInt values. 977 // 978 const Type *ETy = CA->getType()->getElementType(); 979 if (CA->isString()) { 980 Out << "c\""; 981 PrintEscapedString(CA->getAsString(), Out); 982 Out << '"'; 983 } else { // Cannot output in string format... 984 Out << '['; 985 if (CA->getNumOperands()) { 986 TypePrinter.print(ETy, Out); 987 Out << ' '; 988 WriteAsOperandInternal(Out, CA->getOperand(0), 989 &TypePrinter, Machine); 990 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) { 991 Out << ", "; 992 TypePrinter.print(ETy, Out); 993 Out << ' '; 994 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine); 995 } 996 } 997 Out << ']'; 998 } 999 return; 1000 } 1001 1002 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) { 1003 if (CS->getType()->isPacked()) 1004 Out << '<'; 1005 Out << '{'; 1006 unsigned N = CS->getNumOperands(); 1007 if (N) { 1008 Out << ' '; 1009 TypePrinter.print(CS->getOperand(0)->getType(), Out); 1010 Out << ' '; 1011 1012 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine); 1013 1014 for (unsigned i = 1; i < N; i++) { 1015 Out << ", "; 1016 TypePrinter.print(CS->getOperand(i)->getType(), Out); 1017 Out << ' '; 1018 1019 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine); 1020 } 1021 Out << ' '; 1022 } 1023 1024 Out << '}'; 1025 if (CS->getType()->isPacked()) 1026 Out << '>'; 1027 return; 1028 } 1029 1030 if (const ConstantUnion *CU = dyn_cast<ConstantUnion>(CV)) { 1031 Out << "{ "; 1032 TypePrinter.print(CU->getOperand(0)->getType(), Out); 1033 Out << ' '; 1034 WriteAsOperandInternal(Out, CU->getOperand(0), &TypePrinter, Machine); 1035 Out << " }"; 1036 return; 1037 } 1038 1039 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) { 1040 const Type *ETy = CP->getType()->getElementType(); 1041 assert(CP->getNumOperands() > 0 && 1042 "Number of operands for a PackedConst must be > 0"); 1043 Out << '<'; 1044 TypePrinter.print(ETy, Out); 1045 Out << ' '; 1046 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine); 1047 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) { 1048 Out << ", "; 1049 TypePrinter.print(ETy, Out); 1050 Out << ' '; 1051 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine); 1052 } 1053 Out << '>'; 1054 return; 1055 } 1056 1057 if (isa<ConstantPointerNull>(CV)) { 1058 Out << "null"; 1059 return; 1060 } 1061 1062 if (isa<UndefValue>(CV)) { 1063 Out << "undef"; 1064 return; 1065 } 1066 1067 if (const MDNode *Node = dyn_cast<MDNode>(CV)) { 1068 Out << "!" << Machine->getMetadataSlot(Node); 1069 return; 1070 } 1071 1072 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 1073 Out << CE->getOpcodeName(); 1074 WriteOptimizationInfo(Out, CE); 1075 if (CE->isCompare()) 1076 Out << ' ' << getPredicateText(CE->getPredicate()); 1077 Out << " ("; 1078 1079 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) { 1080 TypePrinter.print((*OI)->getType(), Out); 1081 Out << ' '; 1082 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine); 1083 if (OI+1 != CE->op_end()) 1084 Out << ", "; 1085 } 1086 1087 if (CE->hasIndices()) { 1088 const SmallVector<unsigned, 4> &Indices = CE->getIndices(); 1089 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 1090 Out << ", " << Indices[i]; 1091 } 1092 1093 if (CE->isCast()) { 1094 Out << " to "; 1095 TypePrinter.print(CE->getType(), Out); 1096 } 1097 1098 Out << ')'; 1099 return; 1100 } 1101 1102 Out << "<placeholder or erroneous Constant>"; 1103} 1104 1105static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node, 1106 TypePrinting *TypePrinter, 1107 SlotTracker *Machine) { 1108 Out << "!{"; 1109 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) { 1110 const Value *V = Node->getOperand(mi); 1111 if (V == 0) 1112 Out << "null"; 1113 else { 1114 TypePrinter->print(V->getType(), Out); 1115 Out << ' '; 1116 WriteAsOperandInternal(Out, Node->getOperand(mi), 1117 TypePrinter, Machine); 1118 } 1119 if (mi + 1 != me) 1120 Out << ", "; 1121 } 1122 1123 Out << "}"; 1124} 1125 1126 1127/// WriteAsOperand - Write the name of the specified value out to the specified 1128/// ostream. This can be useful when you just want to print int %reg126, not 1129/// the whole instruction that generated it. 1130/// 1131static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 1132 TypePrinting *TypePrinter, 1133 SlotTracker *Machine) { 1134 if (V->hasName()) { 1135 PrintLLVMName(Out, V); 1136 return; 1137 } 1138 1139 const Constant *CV = dyn_cast<Constant>(V); 1140 if (CV && !isa<GlobalValue>(CV)) { 1141 assert(TypePrinter && "Constants require TypePrinting!"); 1142 WriteConstantInt(Out, CV, *TypePrinter, Machine); 1143 return; 1144 } 1145 1146 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 1147 Out << "asm "; 1148 if (IA->hasSideEffects()) 1149 Out << "sideeffect "; 1150 if (IA->isAlignStack()) 1151 Out << "alignstack "; 1152 Out << '"'; 1153 PrintEscapedString(IA->getAsmString(), Out); 1154 Out << "\", \""; 1155 PrintEscapedString(IA->getConstraintString(), Out); 1156 Out << '"'; 1157 return; 1158 } 1159 1160 if (const MDNode *N = dyn_cast<MDNode>(V)) { 1161 if (N->isFunctionLocal()) { 1162 // Print metadata inline, not via slot reference number. 1163 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine); 1164 return; 1165 } 1166 1167 if (!Machine) 1168 Machine = createSlotTracker(V); 1169 Out << '!' << Machine->getMetadataSlot(N); 1170 return; 1171 } 1172 1173 if (const MDString *MDS = dyn_cast<MDString>(V)) { 1174 Out << "!\""; 1175 PrintEscapedString(MDS->getString(), Out); 1176 Out << '"'; 1177 return; 1178 } 1179 1180 if (V->getValueID() == Value::PseudoSourceValueVal || 1181 V->getValueID() == Value::FixedStackPseudoSourceValueVal) { 1182 V->print(Out); 1183 return; 1184 } 1185 1186 char Prefix = '%'; 1187 int Slot; 1188 if (Machine) { 1189 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 1190 Slot = Machine->getGlobalSlot(GV); 1191 Prefix = '@'; 1192 } else { 1193 Slot = Machine->getLocalSlot(V); 1194 } 1195 } else { 1196 Machine = createSlotTracker(V); 1197 if (Machine) { 1198 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 1199 Slot = Machine->getGlobalSlot(GV); 1200 Prefix = '@'; 1201 } else { 1202 Slot = Machine->getLocalSlot(V); 1203 } 1204 delete Machine; 1205 } else { 1206 Slot = -1; 1207 } 1208 } 1209 1210 if (Slot != -1) 1211 Out << Prefix << Slot; 1212 else 1213 Out << "<badref>"; 1214} 1215 1216void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, 1217 bool PrintType, const Module *Context) { 1218 1219 // Fast path: Don't construct and populate a TypePrinting object if we 1220 // won't be needing any types printed. 1221 if (!PrintType && 1222 (!isa<Constant>(V) || V->hasName() || isa<GlobalValue>(V))) { 1223 WriteAsOperandInternal(Out, V, 0, 0); 1224 return; 1225 } 1226 1227 if (Context == 0) Context = getModuleFromVal(V); 1228 1229 TypePrinting TypePrinter; 1230 std::vector<const Type*> NumberedTypes; 1231 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context); 1232 if (PrintType) { 1233 TypePrinter.print(V->getType(), Out); 1234 Out << ' '; 1235 } 1236 1237 WriteAsOperandInternal(Out, V, &TypePrinter, 0); 1238} 1239 1240namespace { 1241 1242class AssemblyWriter { 1243 formatted_raw_ostream &Out; 1244 SlotTracker &Machine; 1245 const Module *TheModule; 1246 TypePrinting TypePrinter; 1247 AssemblyAnnotationWriter *AnnotationWriter; 1248 std::vector<const Type*> NumberedTypes; 1249 1250public: 1251 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 1252 const Module *M, 1253 AssemblyAnnotationWriter *AAW) 1254 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) { 1255 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M); 1256 } 1257 1258 void printMDNodeBody(const MDNode *MD); 1259 void printNamedMDNode(const NamedMDNode *NMD); 1260 1261 void printModule(const Module *M); 1262 1263 void writeOperand(const Value *Op, bool PrintType); 1264 void writeParamOperand(const Value *Operand, Attributes Attrs); 1265 1266 void writeAllMDNodes(); 1267 1268 void printTypeSymbolTable(const TypeSymbolTable &ST); 1269 void printGlobal(const GlobalVariable *GV); 1270 void printAlias(const GlobalAlias *GV); 1271 void printFunction(const Function *F); 1272 void printArgument(const Argument *FA, Attributes Attrs); 1273 void printBasicBlock(const BasicBlock *BB); 1274 void printInstruction(const Instruction &I); 1275 1276private: 1277 // printInfoComment - Print a little comment after the instruction indicating 1278 // which slot it occupies. 1279 void printInfoComment(const Value &V); 1280}; 1281} // end of anonymous namespace 1282 1283void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) { 1284 if (Operand == 0) { 1285 Out << "<null operand!>"; 1286 return; 1287 } 1288 if (PrintType) { 1289 TypePrinter.print(Operand->getType(), Out); 1290 Out << ' '; 1291 } 1292 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine); 1293} 1294 1295void AssemblyWriter::writeParamOperand(const Value *Operand, 1296 Attributes Attrs) { 1297 if (Operand == 0) { 1298 Out << "<null operand!>"; 1299 return; 1300 } 1301 1302 // Print the type 1303 TypePrinter.print(Operand->getType(), Out); 1304 // Print parameter attributes list 1305 if (Attrs != Attribute::None) 1306 Out << ' ' << Attribute::getAsString(Attrs); 1307 Out << ' '; 1308 // Print the operand 1309 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine); 1310} 1311 1312void AssemblyWriter::printModule(const Module *M) { 1313 if (!M->getModuleIdentifier().empty() && 1314 // Don't print the ID if it will start a new line (which would 1315 // require a comment char before it). 1316 M->getModuleIdentifier().find('\n') == std::string::npos) 1317 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 1318 1319 if (!M->getDataLayout().empty()) 1320 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n"; 1321 if (!M->getTargetTriple().empty()) 1322 Out << "target triple = \"" << M->getTargetTriple() << "\"\n"; 1323 1324 if (!M->getModuleInlineAsm().empty()) { 1325 // Split the string into lines, to make it easier to read the .ll file. 1326 std::string Asm = M->getModuleInlineAsm(); 1327 size_t CurPos = 0; 1328 size_t NewLine = Asm.find_first_of('\n', CurPos); 1329 Out << '\n'; 1330 while (NewLine != std::string::npos) { 1331 // We found a newline, print the portion of the asm string from the 1332 // last newline up to this newline. 1333 Out << "module asm \""; 1334 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine), 1335 Out); 1336 Out << "\"\n"; 1337 CurPos = NewLine+1; 1338 NewLine = Asm.find_first_of('\n', CurPos); 1339 } 1340 Out << "module asm \""; 1341 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out); 1342 Out << "\"\n"; 1343 } 1344 1345 // Loop over the dependent libraries and emit them. 1346 Module::lib_iterator LI = M->lib_begin(); 1347 Module::lib_iterator LE = M->lib_end(); 1348 if (LI != LE) { 1349 Out << '\n'; 1350 Out << "deplibs = [ "; 1351 while (LI != LE) { 1352 Out << '"' << *LI << '"'; 1353 ++LI; 1354 if (LI != LE) 1355 Out << ", "; 1356 } 1357 Out << " ]"; 1358 } 1359 1360 // Loop over the symbol table, emitting all id'd types. 1361 if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n'; 1362 printTypeSymbolTable(M->getTypeSymbolTable()); 1363 1364 // Output all globals. 1365 if (!M->global_empty()) Out << '\n'; 1366 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); 1367 I != E; ++I) 1368 printGlobal(I); 1369 1370 // Output all aliases. 1371 if (!M->alias_empty()) Out << "\n"; 1372 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end(); 1373 I != E; ++I) 1374 printAlias(I); 1375 1376 // Output all of the functions. 1377 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) 1378 printFunction(I); 1379 1380 // Output named metadata. 1381 if (!M->named_metadata_empty()) Out << '\n'; 1382 1383 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(), 1384 E = M->named_metadata_end(); I != E; ++I) 1385 printNamedMDNode(I); 1386 1387 // Output metadata. 1388 if (!Machine.mdn_empty()) { 1389 Out << '\n'; 1390 writeAllMDNodes(); 1391 } 1392} 1393 1394void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) { 1395 Out << "!" << NMD->getName() << " = !{"; 1396 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 1397 if (i) Out << ", "; 1398 if (MDNode *MD = NMD->getOperand(i)) 1399 Out << '!' << Machine.getMetadataSlot(MD); 1400 else 1401 Out << "null"; 1402 } 1403 Out << "}\n"; 1404} 1405 1406 1407static void PrintLinkage(GlobalValue::LinkageTypes LT, 1408 formatted_raw_ostream &Out) { 1409 switch (LT) { 1410 case GlobalValue::ExternalLinkage: break; 1411 case GlobalValue::PrivateLinkage: Out << "private "; break; 1412 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break; 1413 case GlobalValue::InternalLinkage: Out << "internal "; break; 1414 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break; 1415 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break; 1416 case GlobalValue::WeakAnyLinkage: Out << "weak "; break; 1417 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break; 1418 case GlobalValue::CommonLinkage: Out << "common "; break; 1419 case GlobalValue::AppendingLinkage: Out << "appending "; break; 1420 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break; 1421 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break; 1422 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break; 1423 case GlobalValue::AvailableExternallyLinkage: 1424 Out << "available_externally "; 1425 break; 1426 } 1427} 1428 1429 1430static void PrintVisibility(GlobalValue::VisibilityTypes Vis, 1431 formatted_raw_ostream &Out) { 1432 switch (Vis) { 1433 case GlobalValue::DefaultVisibility: break; 1434 case GlobalValue::HiddenVisibility: Out << "hidden "; break; 1435 case GlobalValue::ProtectedVisibility: Out << "protected "; break; 1436 } 1437} 1438 1439void AssemblyWriter::printGlobal(const GlobalVariable *GV) { 1440 if (GV->isMaterializable()) 1441 Out << "; Materializable\n"; 1442 1443 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine); 1444 Out << " = "; 1445 1446 if (!GV->hasInitializer() && GV->hasExternalLinkage()) 1447 Out << "external "; 1448 1449 PrintLinkage(GV->getLinkage(), Out); 1450 PrintVisibility(GV->getVisibility(), Out); 1451 1452 if (GV->isThreadLocal()) Out << "thread_local "; 1453 if (unsigned AddressSpace = GV->getType()->getAddressSpace()) 1454 Out << "addrspace(" << AddressSpace << ") "; 1455 Out << (GV->isConstant() ? "constant " : "global "); 1456 TypePrinter.print(GV->getType()->getElementType(), Out); 1457 1458 if (GV->hasInitializer()) { 1459 Out << ' '; 1460 writeOperand(GV->getInitializer(), false); 1461 } 1462 1463 if (GV->hasSection()) 1464 Out << ", section \"" << GV->getSection() << '"'; 1465 if (GV->getAlignment()) 1466 Out << ", align " << GV->getAlignment(); 1467 1468 printInfoComment(*GV); 1469 Out << '\n'; 1470} 1471 1472void AssemblyWriter::printAlias(const GlobalAlias *GA) { 1473 if (GA->isMaterializable()) 1474 Out << "; Materializable\n"; 1475 1476 // Don't crash when dumping partially built GA 1477 if (!GA->hasName()) 1478 Out << "<<nameless>> = "; 1479 else { 1480 PrintLLVMName(Out, GA); 1481 Out << " = "; 1482 } 1483 PrintVisibility(GA->getVisibility(), Out); 1484 1485 Out << "alias "; 1486 1487 PrintLinkage(GA->getLinkage(), Out); 1488 1489 const Constant *Aliasee = GA->getAliasee(); 1490 1491 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) { 1492 TypePrinter.print(GV->getType(), Out); 1493 Out << ' '; 1494 PrintLLVMName(Out, GV); 1495 } else if (const Function *F = dyn_cast<Function>(Aliasee)) { 1496 TypePrinter.print(F->getFunctionType(), Out); 1497 Out << "* "; 1498 1499 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine); 1500 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) { 1501 TypePrinter.print(GA->getType(), Out); 1502 Out << ' '; 1503 PrintLLVMName(Out, GA); 1504 } else { 1505 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee); 1506 // The only valid GEP is an all zero GEP. 1507 assert((CE->getOpcode() == Instruction::BitCast || 1508 CE->getOpcode() == Instruction::GetElementPtr) && 1509 "Unsupported aliasee"); 1510 writeOperand(CE, false); 1511 } 1512 1513 printInfoComment(*GA); 1514 Out << '\n'; 1515} 1516 1517void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) { 1518 // Emit all numbered types. 1519 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) { 1520 Out << '%' << i << " = type "; 1521 1522 // Make sure we print out at least one level of the type structure, so 1523 // that we do not get %2 = type %2 1524 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out); 1525 Out << '\n'; 1526 } 1527 1528 // Print the named types. 1529 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end(); 1530 TI != TE; ++TI) { 1531 PrintLLVMName(Out, TI->first, LocalPrefix); 1532 Out << " = type "; 1533 1534 // Make sure we print out at least one level of the type structure, so 1535 // that we do not get %FILE = type %FILE 1536 TypePrinter.printAtLeastOneLevel(TI->second, Out); 1537 Out << '\n'; 1538 } 1539} 1540 1541/// printFunction - Print all aspects of a function. 1542/// 1543void AssemblyWriter::printFunction(const Function *F) { 1544 // Print out the return type and name. 1545 Out << '\n'; 1546 1547 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out); 1548 1549 if (F->isMaterializable()) 1550 Out << "; Materializable\n"; 1551 1552 if (F->isDeclaration()) 1553 Out << "declare "; 1554 else 1555 Out << "define "; 1556 1557 PrintLinkage(F->getLinkage(), Out); 1558 PrintVisibility(F->getVisibility(), Out); 1559 1560 // Print the calling convention. 1561 switch (F->getCallingConv()) { 1562 case CallingConv::C: break; // default 1563 case CallingConv::Fast: Out << "fastcc "; break; 1564 case CallingConv::Cold: Out << "coldcc "; break; 1565 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break; 1566 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 1567 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break; 1568 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break; 1569 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break; 1570 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break; 1571 default: Out << "cc" << F->getCallingConv() << " "; break; 1572 } 1573 1574 const FunctionType *FT = F->getFunctionType(); 1575 const AttrListPtr &Attrs = F->getAttributes(); 1576 Attributes RetAttrs = Attrs.getRetAttributes(); 1577 if (RetAttrs != Attribute::None) 1578 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' '; 1579 TypePrinter.print(F->getReturnType(), Out); 1580 Out << ' '; 1581 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine); 1582 Out << '('; 1583 Machine.incorporateFunction(F); 1584 1585 // Loop over the arguments, printing them... 1586 1587 unsigned Idx = 1; 1588 if (!F->isDeclaration()) { 1589 // If this isn't a declaration, print the argument names as well. 1590 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 1591 I != E; ++I) { 1592 // Insert commas as we go... the first arg doesn't get a comma 1593 if (I != F->arg_begin()) Out << ", "; 1594 printArgument(I, Attrs.getParamAttributes(Idx)); 1595 Idx++; 1596 } 1597 } else { 1598 // Otherwise, print the types from the function type. 1599 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1600 // Insert commas as we go... the first arg doesn't get a comma 1601 if (i) Out << ", "; 1602 1603 // Output type... 1604 TypePrinter.print(FT->getParamType(i), Out); 1605 1606 Attributes ArgAttrs = Attrs.getParamAttributes(i+1); 1607 if (ArgAttrs != Attribute::None) 1608 Out << ' ' << Attribute::getAsString(ArgAttrs); 1609 } 1610 } 1611 1612 // Finish printing arguments... 1613 if (FT->isVarArg()) { 1614 if (FT->getNumParams()) Out << ", "; 1615 Out << "..."; // Output varargs portion of signature! 1616 } 1617 Out << ')'; 1618 Attributes FnAttrs = Attrs.getFnAttributes(); 1619 if (FnAttrs != Attribute::None) 1620 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes()); 1621 if (F->hasSection()) 1622 Out << " section \"" << F->getSection() << '"'; 1623 if (F->getAlignment()) 1624 Out << " align " << F->getAlignment(); 1625 if (F->hasGC()) 1626 Out << " gc \"" << F->getGC() << '"'; 1627 if (F->isDeclaration()) { 1628 Out << "\n"; 1629 } else { 1630 Out << " {"; 1631 1632 // Output all of its basic blocks... for the function 1633 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I) 1634 printBasicBlock(I); 1635 1636 Out << "}\n"; 1637 } 1638 1639 Machine.purgeFunction(); 1640} 1641 1642/// printArgument - This member is called for every argument that is passed into 1643/// the function. Simply print it out 1644/// 1645void AssemblyWriter::printArgument(const Argument *Arg, 1646 Attributes Attrs) { 1647 // Output type... 1648 TypePrinter.print(Arg->getType(), Out); 1649 1650 // Output parameter attributes list 1651 if (Attrs != Attribute::None) 1652 Out << ' ' << Attribute::getAsString(Attrs); 1653 1654 // Output name, if available... 1655 if (Arg->hasName()) { 1656 Out << ' '; 1657 PrintLLVMName(Out, Arg); 1658 } 1659} 1660 1661/// printBasicBlock - This member is called for each basic block in a method. 1662/// 1663void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { 1664 if (BB->hasName()) { // Print out the label if it exists... 1665 Out << "\n"; 1666 PrintLLVMName(Out, BB->getName(), LabelPrefix); 1667 Out << ':'; 1668 } else if (!BB->use_empty()) { // Don't print block # of no uses... 1669 Out << "\n; <label>:"; 1670 int Slot = Machine.getLocalSlot(BB); 1671 if (Slot != -1) 1672 Out << Slot; 1673 else 1674 Out << "<badref>"; 1675 } 1676 1677 if (BB->getParent() == 0) { 1678 Out.PadToColumn(50); 1679 Out << "; Error: Block without parent!"; 1680 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block? 1681 // Output predecessors for the block... 1682 Out.PadToColumn(50); 1683 Out << ";"; 1684 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB); 1685 1686 if (PI == PE) { 1687 Out << " No predecessors!"; 1688 } else { 1689 Out << " preds = "; 1690 writeOperand(*PI, false); 1691 for (++PI; PI != PE; ++PI) { 1692 Out << ", "; 1693 writeOperand(*PI, false); 1694 } 1695 } 1696 } 1697 1698 Out << "\n"; 1699 1700 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out); 1701 1702 // Output all of the instructions in the basic block... 1703 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 1704 printInstruction(*I); 1705 Out << '\n'; 1706 } 1707 1708 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out); 1709} 1710 1711/// printInfoComment - Print a little comment after the instruction indicating 1712/// which slot it occupies. 1713/// 1714void AssemblyWriter::printInfoComment(const Value &V) { 1715 if (AnnotationWriter) { 1716 AnnotationWriter->printInfoComment(V, Out); 1717 return; 1718 } 1719 1720 if (V.getType()->isVoidTy()) return; 1721 1722 Out.PadToColumn(50); 1723 Out << "; <"; 1724 TypePrinter.print(V.getType(), Out); 1725 Out << "> [#uses=" << V.getNumUses() << ']'; // Output # uses 1726} 1727 1728// This member is called for each Instruction in a function.. 1729void AssemblyWriter::printInstruction(const Instruction &I) { 1730 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out); 1731 1732 // Print out indentation for an instruction. 1733 Out << " "; 1734 1735 // Print out name if it exists... 1736 if (I.hasName()) { 1737 PrintLLVMName(Out, &I); 1738 Out << " = "; 1739 } else if (!I.getType()->isVoidTy()) { 1740 // Print out the def slot taken. 1741 int SlotNum = Machine.getLocalSlot(&I); 1742 if (SlotNum == -1) 1743 Out << "<badref> = "; 1744 else 1745 Out << '%' << SlotNum << " = "; 1746 } 1747 1748 // If this is a volatile load or store, print out the volatile marker. 1749 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) || 1750 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) { 1751 Out << "volatile "; 1752 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) { 1753 // If this is a call, check if it's a tail call. 1754 Out << "tail "; 1755 } 1756 1757 // Print out the opcode... 1758 Out << I.getOpcodeName(); 1759 1760 // Print out optimization information. 1761 WriteOptimizationInfo(Out, &I); 1762 1763 // Print out the compare instruction predicates 1764 if (const CmpInst *CI = dyn_cast<CmpInst>(&I)) 1765 Out << ' ' << getPredicateText(CI->getPredicate()); 1766 1767 // Print out the type of the operands... 1768 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0; 1769 1770 // Special case conditional branches to swizzle the condition out to the front 1771 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) { 1772 BranchInst &BI(cast<BranchInst>(I)); 1773 Out << ' '; 1774 writeOperand(BI.getCondition(), true); 1775 Out << ", "; 1776 writeOperand(BI.getSuccessor(0), true); 1777 Out << ", "; 1778 writeOperand(BI.getSuccessor(1), true); 1779 1780 } else if (isa<SwitchInst>(I)) { 1781 // Special case switch instruction to get formatting nice and correct. 1782 Out << ' '; 1783 writeOperand(Operand , true); 1784 Out << ", "; 1785 writeOperand(I.getOperand(1), true); 1786 Out << " ["; 1787 1788 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) { 1789 Out << "\n "; 1790 writeOperand(I.getOperand(op ), true); 1791 Out << ", "; 1792 writeOperand(I.getOperand(op+1), true); 1793 } 1794 Out << "\n ]"; 1795 } else if (isa<IndirectBrInst>(I)) { 1796 // Special case indirectbr instruction to get formatting nice and correct. 1797 Out << ' '; 1798 writeOperand(Operand, true); 1799 Out << ", ["; 1800 1801 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 1802 if (i != 1) 1803 Out << ", "; 1804 writeOperand(I.getOperand(i), true); 1805 } 1806 Out << ']'; 1807 } else if (isa<PHINode>(I)) { 1808 Out << ' '; 1809 TypePrinter.print(I.getType(), Out); 1810 Out << ' '; 1811 1812 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) { 1813 if (op) Out << ", "; 1814 Out << "[ "; 1815 writeOperand(I.getOperand(op ), false); Out << ", "; 1816 writeOperand(I.getOperand(op+1), false); Out << " ]"; 1817 } 1818 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) { 1819 Out << ' '; 1820 writeOperand(I.getOperand(0), true); 1821 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i) 1822 Out << ", " << *i; 1823 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) { 1824 Out << ' '; 1825 writeOperand(I.getOperand(0), true); Out << ", "; 1826 writeOperand(I.getOperand(1), true); 1827 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i) 1828 Out << ", " << *i; 1829 } else if (isa<ReturnInst>(I) && !Operand) { 1830 Out << " void"; 1831 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 1832 // Print the calling convention being used. 1833 switch (CI->getCallingConv()) { 1834 case CallingConv::C: break; // default 1835 case CallingConv::Fast: Out << " fastcc"; break; 1836 case CallingConv::Cold: Out << " coldcc"; break; 1837 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break; 1838 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break; 1839 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break; 1840 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break; 1841 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break; 1842 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break; 1843 default: Out << " cc" << CI->getCallingConv(); break; 1844 } 1845 1846 const PointerType *PTy = cast<PointerType>(Operand->getType()); 1847 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1848 const Type *RetTy = FTy->getReturnType(); 1849 const AttrListPtr &PAL = CI->getAttributes(); 1850 1851 if (PAL.getRetAttributes() != Attribute::None) 1852 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes()); 1853 1854 // If possible, print out the short form of the call instruction. We can 1855 // only do this if the first argument is a pointer to a nonvararg function, 1856 // and if the return type is not a pointer to a function. 1857 // 1858 Out << ' '; 1859 if (!FTy->isVarArg() && 1860 (!RetTy->isPointerTy() || 1861 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) { 1862 TypePrinter.print(RetTy, Out); 1863 Out << ' '; 1864 writeOperand(Operand, false); 1865 } else { 1866 writeOperand(Operand, true); 1867 } 1868 Out << '('; 1869 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) { 1870 if (op > 1) 1871 Out << ", "; 1872 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op)); 1873 } 1874 Out << ')'; 1875 if (PAL.getFnAttributes() != Attribute::None) 1876 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes()); 1877 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 1878 const PointerType *PTy = cast<PointerType>(Operand->getType()); 1879 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1880 const Type *RetTy = FTy->getReturnType(); 1881 const AttrListPtr &PAL = II->getAttributes(); 1882 1883 // Print the calling convention being used. 1884 switch (II->getCallingConv()) { 1885 case CallingConv::C: break; // default 1886 case CallingConv::Fast: Out << " fastcc"; break; 1887 case CallingConv::Cold: Out << " coldcc"; break; 1888 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break; 1889 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break; 1890 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break; 1891 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break; 1892 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break; 1893 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break; 1894 default: Out << " cc" << II->getCallingConv(); break; 1895 } 1896 1897 if (PAL.getRetAttributes() != Attribute::None) 1898 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes()); 1899 1900 // If possible, print out the short form of the invoke instruction. We can 1901 // only do this if the first argument is a pointer to a nonvararg function, 1902 // and if the return type is not a pointer to a function. 1903 // 1904 Out << ' '; 1905 if (!FTy->isVarArg() && 1906 (!RetTy->isPointerTy() || 1907 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) { 1908 TypePrinter.print(RetTy, Out); 1909 Out << ' '; 1910 writeOperand(Operand, false); 1911 } else { 1912 writeOperand(Operand, true); 1913 } 1914 Out << '('; 1915 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) { 1916 if (op > 3) 1917 Out << ", "; 1918 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2)); 1919 } 1920 1921 Out << ')'; 1922 if (PAL.getFnAttributes() != Attribute::None) 1923 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes()); 1924 1925 Out << "\n to "; 1926 writeOperand(II->getNormalDest(), true); 1927 Out << " unwind "; 1928 writeOperand(II->getUnwindDest(), true); 1929 1930 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 1931 Out << ' '; 1932 TypePrinter.print(AI->getType()->getElementType(), Out); 1933 if (!AI->getArraySize() || AI->isArrayAllocation()) { 1934 Out << ", "; 1935 writeOperand(AI->getArraySize(), true); 1936 } 1937 if (AI->getAlignment()) { 1938 Out << ", align " << AI->getAlignment(); 1939 } 1940 } else if (isa<CastInst>(I)) { 1941 if (Operand) { 1942 Out << ' '; 1943 writeOperand(Operand, true); // Work with broken code 1944 } 1945 Out << " to "; 1946 TypePrinter.print(I.getType(), Out); 1947 } else if (isa<VAArgInst>(I)) { 1948 if (Operand) { 1949 Out << ' '; 1950 writeOperand(Operand, true); // Work with broken code 1951 } 1952 Out << ", "; 1953 TypePrinter.print(I.getType(), Out); 1954 } else if (Operand) { // Print the normal way. 1955 1956 // PrintAllTypes - Instructions who have operands of all the same type 1957 // omit the type from all but the first operand. If the instruction has 1958 // different type operands (for example br), then they are all printed. 1959 bool PrintAllTypes = false; 1960 const Type *TheType = Operand->getType(); 1961 1962 // Select, Store and ShuffleVector always print all types. 1963 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) 1964 || isa<ReturnInst>(I)) { 1965 PrintAllTypes = true; 1966 } else { 1967 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) { 1968 Operand = I.getOperand(i); 1969 // note that Operand shouldn't be null, but the test helps make dump() 1970 // more tolerant of malformed IR 1971 if (Operand && Operand->getType() != TheType) { 1972 PrintAllTypes = true; // We have differing types! Print them all! 1973 break; 1974 } 1975 } 1976 } 1977 1978 if (!PrintAllTypes) { 1979 Out << ' '; 1980 TypePrinter.print(TheType, Out); 1981 } 1982 1983 Out << ' '; 1984 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) { 1985 if (i) Out << ", "; 1986 writeOperand(I.getOperand(i), PrintAllTypes); 1987 } 1988 } 1989 1990 // Print post operand alignment for load/store. 1991 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) { 1992 Out << ", align " << cast<LoadInst>(I).getAlignment(); 1993 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) { 1994 Out << ", align " << cast<StoreInst>(I).getAlignment(); 1995 } 1996 1997 // Print Metadata info. 1998 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD; 1999 I.getAllMetadata(InstMD); 2000 if (!InstMD.empty()) { 2001 SmallVector<StringRef, 8> MDNames; 2002 I.getType()->getContext().getMDKindNames(MDNames); 2003 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) { 2004 unsigned Kind = InstMD[i].first; 2005 if (Kind < MDNames.size()) { 2006 Out << ", !" << MDNames[Kind]; 2007 } else { 2008 Out << ", !<unknown kind #" << Kind << ">"; 2009 } 2010 Out << " !" << Machine.getMetadataSlot(InstMD[i].second); 2011 } 2012 } 2013 printInfoComment(I); 2014} 2015 2016static void WriteMDNodeComment(const MDNode *Node, 2017 formatted_raw_ostream &Out) { 2018 if (Node->getNumOperands() < 1) 2019 return; 2020 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0)); 2021 if (!CI) return; 2022 unsigned Val = CI->getZExtValue(); 2023 unsigned Tag = Val & ~LLVMDebugVersionMask; 2024 if (Val < LLVMDebugVersion) 2025 return; 2026 2027 Out.PadToColumn(50); 2028 if (Tag == dwarf::DW_TAG_auto_variable) 2029 Out << "; [ DW_TAG_auto_variable ]"; 2030 else if (Tag == dwarf::DW_TAG_arg_variable) 2031 Out << "; [ DW_TAG_arg_variable ]"; 2032 else if (Tag == dwarf::DW_TAG_return_variable) 2033 Out << "; [ DW_TAG_return_variable ]"; 2034 else if (Tag == dwarf::DW_TAG_vector_type) 2035 Out << "; [ DW_TAG_vector_type ]"; 2036 else if (Tag == dwarf::DW_TAG_user_base) 2037 Out << "; [ DW_TAG_user_base ]"; 2038 else if (const char *TagName = dwarf::TagString(Tag)) 2039 Out << "; [ " << TagName << " ]"; 2040} 2041 2042void AssemblyWriter::writeAllMDNodes() { 2043 SmallVector<const MDNode *, 16> Nodes; 2044 Nodes.resize(Machine.mdn_size()); 2045 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end(); 2046 I != E; ++I) 2047 Nodes[I->second] = cast<MDNode>(I->first); 2048 2049 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { 2050 Out << '!' << i << " = metadata "; 2051 printMDNodeBody(Nodes[i]); 2052 } 2053} 2054 2055void AssemblyWriter::printMDNodeBody(const MDNode *Node) { 2056 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine); 2057 WriteMDNodeComment(Node, Out); 2058 Out << "\n"; 2059} 2060 2061//===----------------------------------------------------------------------===// 2062// External Interface declarations 2063//===----------------------------------------------------------------------===// 2064 2065void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const { 2066 SlotTracker SlotTable(this); 2067 formatted_raw_ostream OS(ROS); 2068 AssemblyWriter W(OS, SlotTable, this, AAW); 2069 W.printModule(this); 2070} 2071 2072void Type::print(raw_ostream &OS) const { 2073 if (this == 0) { 2074 OS << "<null Type>"; 2075 return; 2076 } 2077 TypePrinting().print(this, OS); 2078} 2079 2080void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const { 2081 if (this == 0) { 2082 ROS << "printing a <null> value\n"; 2083 return; 2084 } 2085 formatted_raw_ostream OS(ROS); 2086 if (const Instruction *I = dyn_cast<Instruction>(this)) { 2087 const Function *F = I->getParent() ? I->getParent()->getParent() : 0; 2088 SlotTracker SlotTable(F); 2089 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW); 2090 W.printInstruction(*I); 2091 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) { 2092 SlotTracker SlotTable(BB->getParent()); 2093 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW); 2094 W.printBasicBlock(BB); 2095 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) { 2096 SlotTracker SlotTable(GV->getParent()); 2097 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW); 2098 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV)) 2099 W.printGlobal(V); 2100 else if (const Function *F = dyn_cast<Function>(GV)) 2101 W.printFunction(F); 2102 else 2103 W.printAlias(cast<GlobalAlias>(GV)); 2104 } else if (const MDNode *N = dyn_cast<MDNode>(this)) { 2105 const Function *F = N->getFunction(); 2106 SlotTracker SlotTable(F); 2107 AssemblyWriter W(OS, SlotTable, F ? getModuleFromVal(F) : 0, AAW); 2108 W.printMDNodeBody(N); 2109 } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(this)) { 2110 SlotTracker SlotTable(N->getParent()); 2111 AssemblyWriter W(OS, SlotTable, N->getParent(), AAW); 2112 W.printNamedMDNode(N); 2113 } else if (const Constant *C = dyn_cast<Constant>(this)) { 2114 TypePrinting TypePrinter; 2115 TypePrinter.print(C->getType(), OS); 2116 OS << ' '; 2117 WriteConstantInt(OS, C, TypePrinter, 0); 2118 } else if (isa<InlineAsm>(this) || isa<MDString>(this) || 2119 isa<Argument>(this)) { 2120 WriteAsOperand(OS, this, true, 0); 2121 } else { 2122 // Otherwise we don't know what it is. Call the virtual function to 2123 // allow a subclass to print itself. 2124 printCustom(OS); 2125 } 2126} 2127 2128// Value::printCustom - subclasses should override this to implement printing. 2129void Value::printCustom(raw_ostream &OS) const { 2130 llvm_unreachable("Unknown value to print out!"); 2131} 2132 2133// Value::dump - allow easy printing of Values from the debugger. 2134void Value::dump() const { print(dbgs()); dbgs() << '\n'; } 2135 2136// Type::dump - allow easy printing of Types from the debugger. 2137// This one uses type names from the given context module 2138void Type::dump(const Module *Context) const { 2139 WriteTypeSymbolic(dbgs(), this, Context); 2140 dbgs() << '\n'; 2141} 2142 2143// Type::dump - allow easy printing of Types from the debugger. 2144void Type::dump() const { dump(0); } 2145 2146// Module::dump() - Allow printing of Modules from the debugger. 2147void Module::dump() const { print(dbgs(), 0); } 2148