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