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