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