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