AsmWriter.cpp revision b951bc02839e9862e02e17c7ea83e6437fc13442
1//===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This library implements the functionality defined in llvm/Assembly/Writer.h 11// 12// Note that these routines must be extremely tolerant of various errors in the 13// LLVM code, because it can be used for debugging transformations. 14// 15//===----------------------------------------------------------------------===// 16 17#include "llvm/Assembly/Writer.h" 18#include "llvm/Assembly/PrintModulePass.h" 19#include "llvm/Assembly/AsmAnnotationWriter.h" 20#include "llvm/CallingConv.h" 21#include "llvm/Constants.h" 22#include "llvm/DerivedTypes.h" 23#include "llvm/InlineAsm.h" 24#include "llvm/Instruction.h" 25#include "llvm/Instructions.h" 26#include "llvm/Module.h" 27#include "llvm/SymbolTable.h" 28#include "llvm/ADT/StringExtras.h" 29#include "llvm/ADT/STLExtras.h" 30#include "llvm/Support/CFG.h" 31#include "llvm/Support/MathExtras.h" 32#include "llvm/Support/Streams.h" 33#include <algorithm> 34using namespace llvm; 35 36namespace llvm { 37 38// Make virtual table appear in this compilation unit. 39AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {} 40 41/// This class provides computation of slot numbers for LLVM Assembly writing. 42/// @brief LLVM Assembly Writing Slot Computation. 43class SlotMachine { 44 45/// @name Types 46/// @{ 47public: 48 49 /// @brief A mapping of Values to slot numbers 50 typedef std::map<const Value*, unsigned> ValueMap; 51 52 /// @brief A plane with next slot number and ValueMap 53 struct ValuePlane { 54 unsigned next_slot; ///< The next slot number to use 55 ValueMap map; ///< The map of Value* -> unsigned 56 ValuePlane() { next_slot = 0; } ///< Make sure we start at 0 57 }; 58 59 /// @brief The map of planes by Type 60 typedef std::map<const Type*, ValuePlane> TypedPlanes; 61 62/// @} 63/// @name Constructors 64/// @{ 65public: 66 /// @brief Construct from a module 67 SlotMachine(const Module *M); 68 69 /// @brief Construct from a function, starting out in incorp state. 70 SlotMachine(const Function *F); 71 72/// @} 73/// @name Accessors 74/// @{ 75public: 76 /// Return the slot number of the specified value in it's type 77 /// plane. Its an error to ask for something not in the SlotMachine. 78 /// Its an error to ask for a Type* 79 int getSlot(const Value *V); 80 81/// @} 82/// @name Mutators 83/// @{ 84public: 85 /// If you'd like to deal with a function instead of just a module, use 86 /// this method to get its data into the SlotMachine. 87 void incorporateFunction(const Function *F) { 88 TheFunction = F; 89 FunctionProcessed = false; 90 } 91 92 /// After calling incorporateFunction, use this method to remove the 93 /// most recently incorporated function from the SlotMachine. This 94 /// will reset the state of the machine back to just the module contents. 95 void purgeFunction(); 96 97/// @} 98/// @name Implementation Details 99/// @{ 100private: 101 /// This function does the actual initialization. 102 inline void initialize(); 103 104 /// Values can be crammed into here at will. If they haven't 105 /// been inserted already, they get inserted, otherwise they are ignored. 106 /// Either way, the slot number for the Value* is returned. 107 unsigned getOrCreateSlot(const Value *V); 108 109 /// Insert a value into the value table. Return the slot number 110 /// that it now occupies. BadThings(TM) will happen if you insert a 111 /// Value that's already been inserted. 112 unsigned insertValue(const Value *V); 113 114 /// Add all of the module level global variables (and their initializers) 115 /// and function declarations, but not the contents of those functions. 116 void processModule(); 117 118 /// Add all of the functions arguments, basic blocks, and instructions 119 void processFunction(); 120 121 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT 122 void operator=(const SlotMachine &); // DO NOT IMPLEMENT 123 124/// @} 125/// @name Data 126/// @{ 127public: 128 129 /// @brief The module for which we are holding slot numbers 130 const Module* TheModule; 131 132 /// @brief The function for which we are holding slot numbers 133 const Function* TheFunction; 134 bool FunctionProcessed; 135 136 /// @brief The TypePlanes map for the module level data 137 TypedPlanes mMap; 138 139 /// @brief The TypePlanes map for the function level data 140 TypedPlanes fMap; 141 142/// @} 143 144}; 145 146} // end namespace llvm 147 148static RegisterPass<PrintModulePass> 149X("printm", "Print module to stderr"); 150static RegisterPass<PrintFunctionPass> 151Y("print","Print function to stderr"); 152 153static void WriteAsOperandInternal(std::ostream &Out, const Value *V, 154 std::map<const Type *, std::string> &TypeTable, 155 SlotMachine *Machine); 156 157static const Module *getModuleFromVal(const Value *V) { 158 if (const Argument *MA = dyn_cast<Argument>(V)) 159 return MA->getParent() ? MA->getParent()->getParent() : 0; 160 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 161 return BB->getParent() ? BB->getParent()->getParent() : 0; 162 else if (const Instruction *I = dyn_cast<Instruction>(V)) { 163 const Function *M = I->getParent() ? I->getParent()->getParent() : 0; 164 return M ? M->getParent() : 0; 165 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 166 return GV->getParent(); 167 return 0; 168} 169 170static SlotMachine *createSlotMachine(const Value *V) { 171 if (const Argument *FA = dyn_cast<Argument>(V)) { 172 return new SlotMachine(FA->getParent()); 173 } else if (const Instruction *I = dyn_cast<Instruction>(V)) { 174 return new SlotMachine(I->getParent()->getParent()); 175 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) { 176 return new SlotMachine(BB->getParent()); 177 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){ 178 return new SlotMachine(GV->getParent()); 179 } else if (const Function *Func = dyn_cast<Function>(V)) { 180 return new SlotMachine(Func); 181 } 182 return 0; 183} 184 185// getLLVMName - Turn the specified string into an 'LLVM name', which is either 186// prefixed with % (if the string only contains simple characters) or is 187// surrounded with ""'s (if it has special chars in it). 188static std::string getLLVMName(const std::string &Name, 189 bool prefixName = true) { 190 assert(!Name.empty() && "Cannot get empty name!"); 191 192 // First character cannot start with a number... 193 if (Name[0] >= '0' && Name[0] <= '9') 194 return "\"" + Name + "\""; 195 196 // Scan to see if we have any characters that are not on the "white list" 197 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 198 char C = Name[i]; 199 assert(C != '"' && "Illegal character in LLVM value name!"); 200 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') && 201 C != '-' && C != '.' && C != '_') 202 return "\"" + Name + "\""; 203 } 204 205 // If we get here, then the identifier is legal to use as a "VarID". 206 if (prefixName) 207 return "%"+Name; 208 else 209 return Name; 210} 211 212 213/// fillTypeNameTable - If the module has a symbol table, take all global types 214/// and stuff their names into the TypeNames map. 215/// 216static void fillTypeNameTable(const Module *M, 217 std::map<const Type *, std::string> &TypeNames) { 218 if (!M) return; 219 const SymbolTable &ST = M->getSymbolTable(); 220 SymbolTable::type_const_iterator TI = ST.type_begin(); 221 for (; TI != ST.type_end(); ++TI) { 222 // As a heuristic, don't insert pointer to primitive types, because 223 // they are used too often to have a single useful name. 224 // 225 const Type *Ty = cast<Type>(TI->second); 226 if (!isa<PointerType>(Ty) || 227 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() || 228 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType())) 229 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first))); 230 } 231} 232 233 234 235static void calcTypeName(const Type *Ty, 236 std::vector<const Type *> &TypeStack, 237 std::map<const Type *, std::string> &TypeNames, 238 std::string & Result){ 239 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) { 240 Result += Ty->getDescription(); // Base case 241 return; 242 } 243 244 // Check to see if the type is named. 245 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty); 246 if (I != TypeNames.end()) { 247 Result += I->second; 248 return; 249 } 250 251 if (isa<OpaqueType>(Ty)) { 252 Result += "opaque"; 253 return; 254 } 255 256 // Check to see if the Type is already on the stack... 257 unsigned Slot = 0, CurSize = TypeStack.size(); 258 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type 259 260 // This is another base case for the recursion. In this case, we know 261 // that we have looped back to a type that we have previously visited. 262 // Generate the appropriate upreference to handle this. 263 if (Slot < CurSize) { 264 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference 265 return; 266 } 267 268 TypeStack.push_back(Ty); // Recursive case: Add us to the stack.. 269 270 switch (Ty->getTypeID()) { 271 case Type::FunctionTyID: { 272 const FunctionType *FTy = cast<FunctionType>(Ty); 273 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result); 274 Result += " ("; 275 for (FunctionType::param_iterator I = FTy->param_begin(), 276 E = FTy->param_end(); I != E; ++I) { 277 if (I != FTy->param_begin()) 278 Result += ", "; 279 calcTypeName(*I, TypeStack, TypeNames, Result); 280 } 281 if (FTy->isVarArg()) { 282 if (FTy->getNumParams()) Result += ", "; 283 Result += "..."; 284 } 285 Result += ")"; 286 break; 287 } 288 case Type::StructTyID: { 289 const StructType *STy = cast<StructType>(Ty); 290 if (STy->isPacked()) 291 Result += '<'; 292 Result += "{ "; 293 for (StructType::element_iterator I = STy->element_begin(), 294 E = STy->element_end(); I != E; ++I) { 295 if (I != STy->element_begin()) 296 Result += ", "; 297 calcTypeName(*I, TypeStack, TypeNames, Result); 298 } 299 Result += " }"; 300 if (STy->isPacked()) 301 Result += '>'; 302 break; 303 } 304 case Type::PointerTyID: 305 calcTypeName(cast<PointerType>(Ty)->getElementType(), 306 TypeStack, TypeNames, Result); 307 Result += "*"; 308 break; 309 case Type::ArrayTyID: { 310 const ArrayType *ATy = cast<ArrayType>(Ty); 311 Result += "[" + utostr(ATy->getNumElements()) + " x "; 312 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result); 313 Result += "]"; 314 break; 315 } 316 case Type::PackedTyID: { 317 const PackedType *PTy = cast<PackedType>(Ty); 318 Result += "<" + utostr(PTy->getNumElements()) + " x "; 319 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result); 320 Result += ">"; 321 break; 322 } 323 case Type::OpaqueTyID: 324 Result += "opaque"; 325 break; 326 default: 327 Result += "<unrecognized-type>"; 328 break; 329 } 330 331 TypeStack.pop_back(); // Remove self from stack... 332} 333 334 335/// printTypeInt - The internal guts of printing out a type that has a 336/// potentially named portion. 337/// 338static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty, 339 std::map<const Type *, std::string> &TypeNames) { 340 // Primitive types always print out their description, regardless of whether 341 // they have been named or not. 342 // 343 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) 344 return Out << Ty->getDescription(); 345 346 // Check to see if the type is named. 347 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty); 348 if (I != TypeNames.end()) return Out << I->second; 349 350 // Otherwise we have a type that has not been named but is a derived type. 351 // Carefully recurse the type hierarchy to print out any contained symbolic 352 // names. 353 // 354 std::vector<const Type *> TypeStack; 355 std::string TypeName; 356 calcTypeName(Ty, TypeStack, TypeNames, TypeName); 357 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use 358 return (Out << TypeName); 359} 360 361 362/// WriteTypeSymbolic - This attempts to write the specified type as a symbolic 363/// type, iff there is an entry in the modules symbol table for the specified 364/// type or one of it's component types. This is slower than a simple x << Type 365/// 366std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty, 367 const Module *M) { 368 Out << ' '; 369 370 // If they want us to print out a type, but there is no context, we can't 371 // print it symbolically. 372 if (!M) 373 return Out << Ty->getDescription(); 374 375 std::map<const Type *, std::string> TypeNames; 376 fillTypeNameTable(M, TypeNames); 377 return printTypeInt(Out, Ty, TypeNames); 378} 379 380// PrintEscapedString - Print each character of the specified string, escaping 381// it if it is not printable or if it is an escape char. 382static void PrintEscapedString(const std::string &Str, std::ostream &Out) { 383 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 384 unsigned char C = Str[i]; 385 if (isprint(C) && C != '"' && C != '\\') { 386 Out << C; 387 } else { 388 Out << '\\' 389 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A')) 390 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A')); 391 } 392 } 393} 394 395static const char *getPredicateText(unsigned predicate) { 396 const char * pred = "unknown"; 397 switch (predicate) { 398 case FCmpInst::FCMP_FALSE: pred = "false"; break; 399 case FCmpInst::FCMP_OEQ: pred = "oeq"; break; 400 case FCmpInst::FCMP_OGT: pred = "ogt"; break; 401 case FCmpInst::FCMP_OGE: pred = "oge"; break; 402 case FCmpInst::FCMP_OLT: pred = "olt"; break; 403 case FCmpInst::FCMP_OLE: pred = "ole"; break; 404 case FCmpInst::FCMP_ONE: pred = "one"; break; 405 case FCmpInst::FCMP_ORD: pred = "ord"; break; 406 case FCmpInst::FCMP_UNO: pred = "uno"; break; 407 case FCmpInst::FCMP_UEQ: pred = "ueq"; break; 408 case FCmpInst::FCMP_UGT: pred = "ugt"; break; 409 case FCmpInst::FCMP_UGE: pred = "uge"; break; 410 case FCmpInst::FCMP_ULT: pred = "ult"; break; 411 case FCmpInst::FCMP_ULE: pred = "ule"; break; 412 case FCmpInst::FCMP_UNE: pred = "une"; break; 413 case FCmpInst::FCMP_TRUE: pred = "true"; break; 414 case ICmpInst::ICMP_EQ: pred = "eq"; break; 415 case ICmpInst::ICMP_NE: pred = "ne"; break; 416 case ICmpInst::ICMP_SGT: pred = "sgt"; break; 417 case ICmpInst::ICMP_SGE: pred = "sge"; break; 418 case ICmpInst::ICMP_SLT: pred = "slt"; break; 419 case ICmpInst::ICMP_SLE: pred = "sle"; break; 420 case ICmpInst::ICMP_UGT: pred = "ugt"; break; 421 case ICmpInst::ICMP_UGE: pred = "uge"; break; 422 case ICmpInst::ICMP_ULT: pred = "ult"; break; 423 case ICmpInst::ICMP_ULE: pred = "ule"; break; 424 } 425 return pred; 426} 427 428/// @brief Internal constant writer. 429static void WriteConstantInt(std::ostream &Out, const Constant *CV, 430 std::map<const Type *, std::string> &TypeTable, 431 SlotMachine *Machine) { 432 const int IndentSize = 4; 433 static std::string Indent = "\n"; 434 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) { 435 Out << (CB->getValue() ? "true" : "false"); 436 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 437 Out << CI->getSExtValue(); 438 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 439 // We would like to output the FP constant value in exponential notation, 440 // but we cannot do this if doing so will lose precision. Check here to 441 // make sure that we only output it in exponential format if we can parse 442 // the value back and get the same value. 443 // 444 std::string StrVal = ftostr(CFP->getValue()); 445 446 // Check to make sure that the stringized number is not some string like 447 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that 448 // the string matches the "[-+]?[0-9]" regex. 449 // 450 if ((StrVal[0] >= '0' && StrVal[0] <= '9') || 451 ((StrVal[0] == '-' || StrVal[0] == '+') && 452 (StrVal[1] >= '0' && StrVal[1] <= '9'))) 453 // Reparse stringized version! 454 if (atof(StrVal.c_str()) == CFP->getValue()) { 455 Out << StrVal; 456 return; 457 } 458 459 // Otherwise we could not reparse it to exactly the same value, so we must 460 // output the string in hexadecimal format! 461 assert(sizeof(double) == sizeof(uint64_t) && 462 "assuming that double is 64 bits!"); 463 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue())); 464 465 } else if (isa<ConstantAggregateZero>(CV)) { 466 Out << "zeroinitializer"; 467 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) { 468 // As a special case, print the array as a string if it is an array of 469 // ubytes or an array of sbytes with positive values. 470 // 471 const Type *ETy = CA->getType()->getElementType(); 472 if (CA->isString()) { 473 Out << "c\""; 474 PrintEscapedString(CA->getAsString(), Out); 475 Out << "\""; 476 477 } else { // Cannot output in string format... 478 Out << '['; 479 if (CA->getNumOperands()) { 480 Out << ' '; 481 printTypeInt(Out, ETy, TypeTable); 482 WriteAsOperandInternal(Out, CA->getOperand(0), 483 TypeTable, Machine); 484 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) { 485 Out << ", "; 486 printTypeInt(Out, ETy, TypeTable); 487 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine); 488 } 489 } 490 Out << " ]"; 491 } 492 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) { 493 Out << '{'; 494 unsigned N = CS->getNumOperands(); 495 if (N) { 496 if (N > 2) { 497 Indent += std::string(IndentSize, ' '); 498 Out << Indent; 499 } else { 500 Out << ' '; 501 } 502 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable); 503 504 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine); 505 506 for (unsigned i = 1; i < N; i++) { 507 Out << ", "; 508 if (N > 2) Out << Indent; 509 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable); 510 511 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine); 512 } 513 if (N > 2) Indent.resize(Indent.size() - IndentSize); 514 } 515 516 Out << " }"; 517 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) { 518 const Type *ETy = CP->getType()->getElementType(); 519 assert(CP->getNumOperands() > 0 && 520 "Number of operands for a PackedConst must be > 0"); 521 Out << '<'; 522 Out << ' '; 523 printTypeInt(Out, ETy, TypeTable); 524 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine); 525 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) { 526 Out << ", "; 527 printTypeInt(Out, ETy, TypeTable); 528 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine); 529 } 530 Out << " >"; 531 } else if (isa<ConstantPointerNull>(CV)) { 532 Out << "null"; 533 534 } else if (isa<UndefValue>(CV)) { 535 Out << "undef"; 536 537 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 538 Out << CE->getOpcodeName(); 539 if (CE->isCompare()) 540 Out << " " << getPredicateText(CE->getPredicate()); 541 Out << " ("; 542 543 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) { 544 printTypeInt(Out, (*OI)->getType(), TypeTable); 545 WriteAsOperandInternal(Out, *OI, TypeTable, Machine); 546 if (OI+1 != CE->op_end()) 547 Out << ", "; 548 } 549 550 if (CE->isCast()) { 551 Out << " to "; 552 printTypeInt(Out, CE->getType(), TypeTable); 553 } 554 555 Out << ')'; 556 557 } else { 558 Out << "<placeholder or erroneous Constant>"; 559 } 560} 561 562 563/// WriteAsOperand - Write the name of the specified value out to the specified 564/// ostream. This can be useful when you just want to print int %reg126, not 565/// the whole instruction that generated it. 566/// 567static void WriteAsOperandInternal(std::ostream &Out, const Value *V, 568 std::map<const Type*, std::string> &TypeTable, 569 SlotMachine *Machine) { 570 Out << ' '; 571 if (V->hasName()) 572 Out << getLLVMName(V->getName()); 573 else { 574 const Constant *CV = dyn_cast<Constant>(V); 575 if (CV && !isa<GlobalValue>(CV)) { 576 WriteConstantInt(Out, CV, TypeTable, Machine); 577 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 578 Out << "asm "; 579 if (IA->hasSideEffects()) 580 Out << "sideeffect "; 581 Out << '"'; 582 PrintEscapedString(IA->getAsmString(), Out); 583 Out << "\", \""; 584 PrintEscapedString(IA->getConstraintString(), Out); 585 Out << '"'; 586 } else { 587 int Slot; 588 if (Machine) { 589 Slot = Machine->getSlot(V); 590 } else { 591 Machine = createSlotMachine(V); 592 if (Machine) 593 Slot = Machine->getSlot(V); 594 else 595 Slot = -1; 596 delete Machine; 597 } 598 if (Slot != -1) 599 Out << '%' << Slot; 600 else 601 Out << "<badref>"; 602 } 603 } 604} 605 606/// WriteAsOperand - Write the name of the specified value out to the specified 607/// ostream. This can be useful when you just want to print int %reg126, not 608/// the whole instruction that generated it. 609/// 610std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V, 611 bool PrintType, const Module *Context) { 612 std::map<const Type *, std::string> TypeNames; 613 if (Context == 0) Context = getModuleFromVal(V); 614 615 if (Context) 616 fillTypeNameTable(Context, TypeNames); 617 618 if (PrintType) 619 printTypeInt(Out, V->getType(), TypeNames); 620 621 WriteAsOperandInternal(Out, V, TypeNames, 0); 622 return Out; 623} 624 625 626namespace llvm { 627 628class AssemblyWriter { 629 std::ostream &Out; 630 SlotMachine &Machine; 631 const Module *TheModule; 632 std::map<const Type *, std::string> TypeNames; 633 AssemblyAnnotationWriter *AnnotationWriter; 634public: 635 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M, 636 AssemblyAnnotationWriter *AAW) 637 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) { 638 639 // If the module has a symbol table, take all global types and stuff their 640 // names into the TypeNames map. 641 // 642 fillTypeNameTable(M, TypeNames); 643 } 644 645 inline void write(const Module *M) { printModule(M); } 646 inline void write(const GlobalVariable *G) { printGlobal(G); } 647 inline void write(const Function *F) { printFunction(F); } 648 inline void write(const BasicBlock *BB) { printBasicBlock(BB); } 649 inline void write(const Instruction *I) { printInstruction(*I); } 650 inline void write(const Constant *CPV) { printConstant(CPV); } 651 inline void write(const Type *Ty) { printType(Ty); } 652 653 void writeOperand(const Value *Op, bool PrintType); 654 655 const Module* getModule() { return TheModule; } 656 657private: 658 void printModule(const Module *M); 659 void printSymbolTable(const SymbolTable &ST); 660 void printConstant(const Constant *CPV); 661 void printGlobal(const GlobalVariable *GV); 662 void printFunction(const Function *F); 663 void printArgument(const Argument *FA); 664 void printBasicBlock(const BasicBlock *BB); 665 void printInstruction(const Instruction &I); 666 667 // printType - Go to extreme measures to attempt to print out a short, 668 // symbolic version of a type name. 669 // 670 std::ostream &printType(const Type *Ty) { 671 return printTypeInt(Out, Ty, TypeNames); 672 } 673 674 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type 675 // without considering any symbolic types that we may have equal to it. 676 // 677 std::ostream &printTypeAtLeastOneLevel(const Type *Ty); 678 679 // printInfoComment - Print a little comment after the instruction indicating 680 // which slot it occupies. 681 void printInfoComment(const Value &V); 682}; 683} // end of llvm namespace 684 685/// printTypeAtLeastOneLevel - Print out one level of the possibly complex type 686/// without considering any symbolic types that we may have equal to it. 687/// 688std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) { 689 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) { 690 printType(FTy->getReturnType()) << " ("; 691 for (FunctionType::param_iterator I = FTy->param_begin(), 692 E = FTy->param_end(); I != E; ++I) { 693 if (I != FTy->param_begin()) 694 Out << ", "; 695 printType(*I); 696 } 697 if (FTy->isVarArg()) { 698 if (FTy->getNumParams()) Out << ", "; 699 Out << "..."; 700 } 701 Out << ')'; 702 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) { 703 if (STy->isPacked()) 704 Out << '<'; 705 Out << "{ "; 706 for (StructType::element_iterator I = STy->element_begin(), 707 E = STy->element_end(); I != E; ++I) { 708 if (I != STy->element_begin()) 709 Out << ", "; 710 printType(*I); 711 } 712 Out << " }"; 713 if (STy->isPacked()) 714 Out << '>'; 715 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) { 716 printType(PTy->getElementType()) << '*'; 717 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 718 Out << '[' << ATy->getNumElements() << " x "; 719 printType(ATy->getElementType()) << ']'; 720 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) { 721 Out << '<' << PTy->getNumElements() << " x "; 722 printType(PTy->getElementType()) << '>'; 723 } 724 else if (isa<OpaqueType>(Ty)) { 725 Out << "opaque"; 726 } else { 727 if (!Ty->isPrimitiveType()) 728 Out << "<unknown derived type>"; 729 printType(Ty); 730 } 731 return Out; 732} 733 734 735void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) { 736 if (Operand == 0) { 737 Out << "<null operand!>"; 738 } else { 739 if (PrintType) { Out << ' '; printType(Operand->getType()); } 740 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine); 741 } 742} 743 744 745void AssemblyWriter::printModule(const Module *M) { 746 if (!M->getModuleIdentifier().empty() && 747 // Don't print the ID if it will start a new line (which would 748 // require a comment char before it). 749 M->getModuleIdentifier().find('\n') == std::string::npos) 750 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 751 752 if (!M->getDataLayout().empty()) 753 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n"; 754 755 switch (M->getEndianness()) { 756 case Module::LittleEndian: Out << "target endian = little\n"; break; 757 case Module::BigEndian: Out << "target endian = big\n"; break; 758 case Module::AnyEndianness: break; 759 } 760 switch (M->getPointerSize()) { 761 case Module::Pointer32: Out << "target pointersize = 32\n"; break; 762 case Module::Pointer64: Out << "target pointersize = 64\n"; break; 763 case Module::AnyPointerSize: break; 764 } 765 if (!M->getTargetTriple().empty()) 766 Out << "target triple = \"" << M->getTargetTriple() << "\"\n"; 767 768 if (!M->getModuleInlineAsm().empty()) { 769 // Split the string into lines, to make it easier to read the .ll file. 770 std::string Asm = M->getModuleInlineAsm(); 771 size_t CurPos = 0; 772 size_t NewLine = Asm.find_first_of('\n', CurPos); 773 while (NewLine != std::string::npos) { 774 // We found a newline, print the portion of the asm string from the 775 // last newline up to this newline. 776 Out << "module asm \""; 777 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine), 778 Out); 779 Out << "\"\n"; 780 CurPos = NewLine+1; 781 NewLine = Asm.find_first_of('\n', CurPos); 782 } 783 Out << "module asm \""; 784 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out); 785 Out << "\"\n"; 786 } 787 788 // Loop over the dependent libraries and emit them. 789 Module::lib_iterator LI = M->lib_begin(); 790 Module::lib_iterator LE = M->lib_end(); 791 if (LI != LE) { 792 Out << "deplibs = [ "; 793 while (LI != LE) { 794 Out << '"' << *LI << '"'; 795 ++LI; 796 if (LI != LE) 797 Out << ", "; 798 } 799 Out << " ]\n"; 800 } 801 802 // Loop over the symbol table, emitting all named constants. 803 printSymbolTable(M->getSymbolTable()); 804 805 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); 806 I != E; ++I) 807 printGlobal(I); 808 809 Out << "\nimplementation ; Functions:\n"; 810 811 // Output all of the functions. 812 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) 813 printFunction(I); 814} 815 816void AssemblyWriter::printGlobal(const GlobalVariable *GV) { 817 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = "; 818 819 if (!GV->hasInitializer()) 820 switch (GV->getLinkage()) { 821 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break; 822 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break; 823 default: Out << "external "; break; 824 } 825 else 826 switch (GV->getLinkage()) { 827 case GlobalValue::InternalLinkage: Out << "internal "; break; 828 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break; 829 case GlobalValue::WeakLinkage: Out << "weak "; break; 830 case GlobalValue::AppendingLinkage: Out << "appending "; break; 831 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break; 832 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break; 833 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break; 834 case GlobalValue::ExternalLinkage: break; 835 case GlobalValue::GhostLinkage: 836 cerr << "GhostLinkage not allowed in AsmWriter!\n"; 837 abort(); 838 } 839 840 Out << (GV->isConstant() ? "constant " : "global "); 841 printType(GV->getType()->getElementType()); 842 843 if (GV->hasInitializer()) { 844 Constant* C = cast<Constant>(GV->getInitializer()); 845 assert(C && "GlobalVar initializer isn't constant?"); 846 writeOperand(GV->getInitializer(), false); 847 } 848 849 if (GV->hasSection()) 850 Out << ", section \"" << GV->getSection() << '"'; 851 if (GV->getAlignment()) 852 Out << ", align " << GV->getAlignment(); 853 854 printInfoComment(*GV); 855 Out << "\n"; 856} 857 858 859// printSymbolTable - Run through symbol table looking for constants 860// and types. Emit their declarations. 861void AssemblyWriter::printSymbolTable(const SymbolTable &ST) { 862 863 // Print the types. 864 for (SymbolTable::type_const_iterator TI = ST.type_begin(); 865 TI != ST.type_end(); ++TI) { 866 Out << "\t" << getLLVMName(TI->first) << " = type "; 867 868 // Make sure we print out at least one level of the type structure, so 869 // that we do not get %FILE = type %FILE 870 // 871 printTypeAtLeastOneLevel(TI->second) << "\n"; 872 } 873 874 // Print the constants, in type plane order. 875 for (SymbolTable::plane_const_iterator PI = ST.plane_begin(); 876 PI != ST.plane_end(); ++PI) { 877 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first); 878 SymbolTable::value_const_iterator VE = ST.value_end(PI->first); 879 880 for (; VI != VE; ++VI) { 881 const Value* V = VI->second; 882 const Constant *CPV = dyn_cast<Constant>(V) ; 883 if (CPV && !isa<GlobalValue>(V)) { 884 printConstant(CPV); 885 } 886 } 887 } 888} 889 890 891/// printConstant - Print out a constant pool entry... 892/// 893void AssemblyWriter::printConstant(const Constant *CPV) { 894 // Don't print out unnamed constants, they will be inlined 895 if (!CPV->hasName()) return; 896 897 // Print out name... 898 Out << "\t" << getLLVMName(CPV->getName()) << " ="; 899 900 // Write the value out now. 901 writeOperand(CPV, true); 902 903 printInfoComment(*CPV); 904 Out << "\n"; 905} 906 907/// printFunction - Print all aspects of a function. 908/// 909void AssemblyWriter::printFunction(const Function *F) { 910 // Print out the return type and name... 911 Out << "\n"; 912 913 // Ensure that no local symbols conflict with global symbols. 914 const_cast<Function*>(F)->renameLocalSymbols(); 915 916 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out); 917 918 if (F->isExternal()) 919 switch (F->getLinkage()) { 920 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break; 921 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break; 922 default: Out << "declare "; 923 } 924 else { 925 Out << "define "; 926 switch (F->getLinkage()) { 927 case GlobalValue::InternalLinkage: Out << "internal "; break; 928 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break; 929 case GlobalValue::WeakLinkage: Out << "weak "; break; 930 case GlobalValue::AppendingLinkage: Out << "appending "; break; 931 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break; 932 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break; 933 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break; 934 case GlobalValue::ExternalLinkage: break; 935 case GlobalValue::GhostLinkage: 936 cerr << "GhostLinkage not allowed in AsmWriter!\n"; 937 abort(); 938 } 939 } 940 941 // Print the calling convention. 942 switch (F->getCallingConv()) { 943 case CallingConv::C: break; // default 944 case CallingConv::CSRet: Out << "csretcc "; break; 945 case CallingConv::Fast: Out << "fastcc "; break; 946 case CallingConv::Cold: Out << "coldcc "; break; 947 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break; 948 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 949 default: Out << "cc" << F->getCallingConv() << " "; break; 950 } 951 952 printType(F->getReturnType()) << ' '; 953 if (!F->getName().empty()) 954 Out << getLLVMName(F->getName()); 955 else 956 Out << "\"\""; 957 Out << '('; 958 Machine.incorporateFunction(F); 959 960 // Loop over the arguments, printing them... 961 const FunctionType *FT = F->getFunctionType(); 962 963 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 964 I != E; ++I) 965 printArgument(I); 966 967 // Finish printing arguments... 968 if (FT->isVarArg()) { 969 if (FT->getNumParams()) Out << ", "; 970 Out << "..."; // Output varargs portion of signature! 971 } 972 Out << ')'; 973 974 if (F->hasSection()) 975 Out << " section \"" << F->getSection() << '"'; 976 if (F->getAlignment()) 977 Out << " align " << F->getAlignment(); 978 979 if (F->isExternal()) { 980 Out << "\n"; 981 } else { 982 Out << " {"; 983 984 // Output all of its basic blocks... for the function 985 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I) 986 printBasicBlock(I); 987 988 Out << "}\n"; 989 } 990 991 Machine.purgeFunction(); 992} 993 994/// printArgument - This member is called for every argument that is passed into 995/// the function. Simply print it out 996/// 997void AssemblyWriter::printArgument(const Argument *Arg) { 998 // Insert commas as we go... the first arg doesn't get a comma 999 if (Arg != Arg->getParent()->arg_begin()) Out << ", "; 1000 1001 // Output type... 1002 printType(Arg->getType()); 1003 1004 // Output name, if available... 1005 if (Arg->hasName()) 1006 Out << ' ' << getLLVMName(Arg->getName()); 1007} 1008 1009/// printBasicBlock - This member is called for each basic block in a method. 1010/// 1011void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { 1012 if (BB->hasName()) { // Print out the label if it exists... 1013 Out << "\n" << getLLVMName(BB->getName(), false) << ':'; 1014 } else if (!BB->use_empty()) { // Don't print block # of no uses... 1015 Out << "\n; <label>:"; 1016 int Slot = Machine.getSlot(BB); 1017 if (Slot != -1) 1018 Out << Slot; 1019 else 1020 Out << "<badref>"; 1021 } 1022 1023 if (BB->getParent() == 0) 1024 Out << "\t\t; Error: Block without parent!"; 1025 else { 1026 if (BB != &BB->getParent()->front()) { // Not the entry block? 1027 // Output predecessors for the block... 1028 Out << "\t\t;"; 1029 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB); 1030 1031 if (PI == PE) { 1032 Out << " No predecessors!"; 1033 } else { 1034 Out << " preds ="; 1035 writeOperand(*PI, false); 1036 for (++PI; PI != PE; ++PI) { 1037 Out << ','; 1038 writeOperand(*PI, false); 1039 } 1040 } 1041 } 1042 } 1043 1044 Out << "\n"; 1045 1046 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out); 1047 1048 // Output all of the instructions in the basic block... 1049 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) 1050 printInstruction(*I); 1051 1052 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out); 1053} 1054 1055 1056/// printInfoComment - Print a little comment after the instruction indicating 1057/// which slot it occupies. 1058/// 1059void AssemblyWriter::printInfoComment(const Value &V) { 1060 if (V.getType() != Type::VoidTy) { 1061 Out << "\t\t; <"; 1062 printType(V.getType()) << '>'; 1063 1064 if (!V.hasName()) { 1065 int SlotNum = Machine.getSlot(&V); 1066 if (SlotNum == -1) 1067 Out << ":<badref>"; 1068 else 1069 Out << ':' << SlotNum; // Print out the def slot taken. 1070 } 1071 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses 1072 } 1073} 1074 1075// This member is called for each Instruction in a function.. 1076void AssemblyWriter::printInstruction(const Instruction &I) { 1077 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out); 1078 1079 Out << "\t"; 1080 1081 // Print out name if it exists... 1082 if (I.hasName()) 1083 Out << getLLVMName(I.getName()) << " = "; 1084 1085 // If this is a volatile load or store, print out the volatile marker. 1086 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) || 1087 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) { 1088 Out << "volatile "; 1089 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) { 1090 // If this is a call, check if it's a tail call. 1091 Out << "tail "; 1092 } 1093 1094 // Print out the opcode... 1095 Out << I.getOpcodeName(); 1096 1097 // Print out the compare instruction predicates 1098 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) { 1099 Out << " " << getPredicateText(FCI->getPredicate()); 1100 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) { 1101 Out << " " << getPredicateText(ICI->getPredicate()); 1102 } 1103 1104 // Print out the type of the operands... 1105 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0; 1106 1107 // Special case conditional branches to swizzle the condition out to the front 1108 if (isa<BranchInst>(I) && I.getNumOperands() > 1) { 1109 writeOperand(I.getOperand(2), true); 1110 Out << ','; 1111 writeOperand(Operand, true); 1112 Out << ','; 1113 writeOperand(I.getOperand(1), true); 1114 1115 } else if (isa<SwitchInst>(I)) { 1116 // Special case switch statement to get formatting nice and correct... 1117 writeOperand(Operand , true); Out << ','; 1118 writeOperand(I.getOperand(1), true); Out << " ["; 1119 1120 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) { 1121 Out << "\n\t\t"; 1122 writeOperand(I.getOperand(op ), true); Out << ','; 1123 writeOperand(I.getOperand(op+1), true); 1124 } 1125 Out << "\n\t]"; 1126 } else if (isa<PHINode>(I)) { 1127 Out << ' '; 1128 printType(I.getType()); 1129 Out << ' '; 1130 1131 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) { 1132 if (op) Out << ", "; 1133 Out << '['; 1134 writeOperand(I.getOperand(op ), false); Out << ','; 1135 writeOperand(I.getOperand(op+1), false); Out << " ]"; 1136 } 1137 } else if (isa<ReturnInst>(I) && !Operand) { 1138 Out << " void"; 1139 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 1140 // Print the calling convention being used. 1141 switch (CI->getCallingConv()) { 1142 case CallingConv::C: break; // default 1143 case CallingConv::CSRet: Out << " csretcc"; break; 1144 case CallingConv::Fast: Out << " fastcc"; break; 1145 case CallingConv::Cold: Out << " coldcc"; break; 1146 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break; 1147 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 1148 default: Out << " cc" << CI->getCallingConv(); break; 1149 } 1150 1151 const PointerType *PTy = cast<PointerType>(Operand->getType()); 1152 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1153 const Type *RetTy = FTy->getReturnType(); 1154 1155 // If possible, print out the short form of the call instruction. We can 1156 // only do this if the first argument is a pointer to a nonvararg function, 1157 // and if the return type is not a pointer to a function. 1158 // 1159 if (!FTy->isVarArg() && 1160 (!isa<PointerType>(RetTy) || 1161 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) { 1162 Out << ' '; printType(RetTy); 1163 writeOperand(Operand, false); 1164 } else { 1165 writeOperand(Operand, true); 1166 } 1167 Out << '('; 1168 if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true); 1169 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) { 1170 Out << ','; 1171 writeOperand(I.getOperand(op), true); 1172 } 1173 1174 Out << " )"; 1175 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 1176 const PointerType *PTy = cast<PointerType>(Operand->getType()); 1177 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1178 const Type *RetTy = FTy->getReturnType(); 1179 1180 // Print the calling convention being used. 1181 switch (II->getCallingConv()) { 1182 case CallingConv::C: break; // default 1183 case CallingConv::CSRet: Out << " csretcc"; break; 1184 case CallingConv::Fast: Out << " fastcc"; break; 1185 case CallingConv::Cold: Out << " coldcc"; break; 1186 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break; 1187 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 1188 default: Out << " cc" << II->getCallingConv(); break; 1189 } 1190 1191 // If possible, print out the short form of the invoke instruction. We can 1192 // only do this if the first argument is a pointer to a nonvararg function, 1193 // and if the return type is not a pointer to a function. 1194 // 1195 if (!FTy->isVarArg() && 1196 (!isa<PointerType>(RetTy) || 1197 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) { 1198 Out << ' '; printType(RetTy); 1199 writeOperand(Operand, false); 1200 } else { 1201 writeOperand(Operand, true); 1202 } 1203 1204 Out << '('; 1205 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true); 1206 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) { 1207 Out << ','; 1208 writeOperand(I.getOperand(op), true); 1209 } 1210 1211 Out << " )\n\t\t\tto"; 1212 writeOperand(II->getNormalDest(), true); 1213 Out << " unwind"; 1214 writeOperand(II->getUnwindDest(), true); 1215 1216 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) { 1217 Out << ' '; 1218 printType(AI->getType()->getElementType()); 1219 if (AI->isArrayAllocation()) { 1220 Out << ','; 1221 writeOperand(AI->getArraySize(), true); 1222 } 1223 if (AI->getAlignment()) { 1224 Out << ", align " << AI->getAlignment(); 1225 } 1226 } else if (isa<CastInst>(I)) { 1227 if (Operand) writeOperand(Operand, true); // Work with broken code 1228 Out << " to "; 1229 printType(I.getType()); 1230 } else if (isa<VAArgInst>(I)) { 1231 if (Operand) writeOperand(Operand, true); // Work with broken code 1232 Out << ", "; 1233 printType(I.getType()); 1234 } else if (Operand) { // Print the normal way... 1235 1236 // PrintAllTypes - Instructions who have operands of all the same type 1237 // omit the type from all but the first operand. If the instruction has 1238 // different type operands (for example br), then they are all printed. 1239 bool PrintAllTypes = false; 1240 const Type *TheType = Operand->getType(); 1241 1242 // Shift Left & Right print both types even for Ubyte LHS, and select prints 1243 // types even if all operands are bools. 1244 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) || 1245 isa<ShuffleVectorInst>(I)) { 1246 PrintAllTypes = true; 1247 } else { 1248 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) { 1249 Operand = I.getOperand(i); 1250 if (Operand->getType() != TheType) { 1251 PrintAllTypes = true; // We have differing types! Print them all! 1252 break; 1253 } 1254 } 1255 } 1256 1257 if (!PrintAllTypes) { 1258 Out << ' '; 1259 printType(TheType); 1260 } 1261 1262 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) { 1263 if (i) Out << ','; 1264 writeOperand(I.getOperand(i), PrintAllTypes); 1265 } 1266 } 1267 1268 printInfoComment(I); 1269 Out << "\n"; 1270} 1271 1272 1273//===----------------------------------------------------------------------===// 1274// External Interface declarations 1275//===----------------------------------------------------------------------===// 1276 1277void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 1278 SlotMachine SlotTable(this); 1279 AssemblyWriter W(o, SlotTable, this, AAW); 1280 W.write(this); 1281} 1282 1283void GlobalVariable::print(std::ostream &o) const { 1284 SlotMachine SlotTable(getParent()); 1285 AssemblyWriter W(o, SlotTable, getParent(), 0); 1286 W.write(this); 1287} 1288 1289void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 1290 SlotMachine SlotTable(getParent()); 1291 AssemblyWriter W(o, SlotTable, getParent(), AAW); 1292 1293 W.write(this); 1294} 1295 1296void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 1297 WriteAsOperand(o, this, true, 0); 1298} 1299 1300void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 1301 SlotMachine SlotTable(getParent()); 1302 AssemblyWriter W(o, SlotTable, 1303 getParent() ? getParent()->getParent() : 0, AAW); 1304 W.write(this); 1305} 1306 1307void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 1308 const Function *F = getParent() ? getParent()->getParent() : 0; 1309 SlotMachine SlotTable(F); 1310 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW); 1311 1312 W.write(this); 1313} 1314 1315void Constant::print(std::ostream &o) const { 1316 if (this == 0) { o << "<null> constant value\n"; return; } 1317 1318 o << ' ' << getType()->getDescription() << ' '; 1319 1320 std::map<const Type *, std::string> TypeTable; 1321 WriteConstantInt(o, this, TypeTable, 0); 1322} 1323 1324void Type::print(std::ostream &o) const { 1325 if (this == 0) 1326 o << "<null Type>"; 1327 else 1328 o << getDescription(); 1329} 1330 1331void Argument::print(std::ostream &o) const { 1332 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0); 1333} 1334 1335// Value::dump - allow easy printing of Values from the debugger. 1336// Located here because so much of the needed functionality is here. 1337void Value::dump() const { print(*cerr.stream()); cerr << '\n'; } 1338 1339// Type::dump - allow easy printing of Values from the debugger. 1340// Located here because so much of the needed functionality is here. 1341void Type::dump() const { print(*cerr.stream()); cerr << '\n'; } 1342 1343//===----------------------------------------------------------------------===// 1344// SlotMachine Implementation 1345//===----------------------------------------------------------------------===// 1346 1347#if 0 1348#define SC_DEBUG(X) cerr << X 1349#else 1350#define SC_DEBUG(X) 1351#endif 1352 1353// Module level constructor. Causes the contents of the Module (sans functions) 1354// to be added to the slot table. 1355SlotMachine::SlotMachine(const Module *M) 1356 : TheModule(M) ///< Saved for lazy initialization. 1357 , TheFunction(0) 1358 , FunctionProcessed(false) 1359{ 1360} 1361 1362// Function level constructor. Causes the contents of the Module and the one 1363// function provided to be added to the slot table. 1364SlotMachine::SlotMachine(const Function *F) 1365 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization 1366 , TheFunction(F) ///< Saved for lazy initialization 1367 , FunctionProcessed(false) 1368{ 1369} 1370 1371inline void SlotMachine::initialize(void) { 1372 if (TheModule) { 1373 processModule(); 1374 TheModule = 0; ///< Prevent re-processing next time we're called. 1375 } 1376 if (TheFunction && !FunctionProcessed) 1377 processFunction(); 1378} 1379 1380// Iterate through all the global variables, functions, and global 1381// variable initializers and create slots for them. 1382void SlotMachine::processModule() { 1383 SC_DEBUG("begin processModule!\n"); 1384 1385 // Add all of the unnamed global variables to the value table. 1386 for (Module::const_global_iterator I = TheModule->global_begin(), 1387 E = TheModule->global_end(); I != E; ++I) 1388 if (!I->hasName()) 1389 getOrCreateSlot(I); 1390 1391 // Add all the unnamed functions to the table. 1392 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 1393 I != E; ++I) 1394 if (!I->hasName()) 1395 getOrCreateSlot(I); 1396 1397 SC_DEBUG("end processModule!\n"); 1398} 1399 1400 1401// Process the arguments, basic blocks, and instructions of a function. 1402void SlotMachine::processFunction() { 1403 SC_DEBUG("begin processFunction!\n"); 1404 1405 // Add all the function arguments with no names. 1406 for(Function::const_arg_iterator AI = TheFunction->arg_begin(), 1407 AE = TheFunction->arg_end(); AI != AE; ++AI) 1408 if (!AI->hasName()) 1409 getOrCreateSlot(AI); 1410 1411 SC_DEBUG("Inserting Instructions:\n"); 1412 1413 // Add all of the basic blocks and instructions with no names. 1414 for (Function::const_iterator BB = TheFunction->begin(), 1415 E = TheFunction->end(); BB != E; ++BB) { 1416 if (!BB->hasName()) 1417 getOrCreateSlot(BB); 1418 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) 1419 if (I->getType() != Type::VoidTy && !I->hasName()) 1420 getOrCreateSlot(I); 1421 } 1422 1423 FunctionProcessed = true; 1424 1425 SC_DEBUG("end processFunction!\n"); 1426} 1427 1428/// Clean up after incorporating a function. This is the only way to get out of 1429/// the function incorporation state that affects the 1430/// getSlot/getOrCreateSlot lock. Function incorporation state is indicated 1431/// by TheFunction != 0. 1432void SlotMachine::purgeFunction() { 1433 SC_DEBUG("begin purgeFunction!\n"); 1434 fMap.clear(); // Simply discard the function level map 1435 TheFunction = 0; 1436 FunctionProcessed = false; 1437 SC_DEBUG("end purgeFunction!\n"); 1438} 1439 1440/// Get the slot number for a value. This function will assert if you 1441/// ask for a Value that hasn't previously been inserted with getOrCreateSlot. 1442/// Types are forbidden because Type does not inherit from Value (any more). 1443int SlotMachine::getSlot(const Value *V) { 1444 assert(V && "Can't get slot for null Value"); 1445 assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 1446 "Can't insert a non-GlobalValue Constant into SlotMachine"); 1447 1448 // Check for uninitialized state and do lazy initialization 1449 this->initialize(); 1450 1451 // Get the type of the value 1452 const Type* VTy = V->getType(); 1453 1454 // Find the type plane in the module map 1455 TypedPlanes::const_iterator MI = mMap.find(VTy); 1456 1457 if (TheFunction) { 1458 // Lookup the type in the function map too 1459 TypedPlanes::const_iterator FI = fMap.find(VTy); 1460 // If there is a corresponding type plane in the function map 1461 if (FI != fMap.end()) { 1462 // Lookup the Value in the function map 1463 ValueMap::const_iterator FVI = FI->second.map.find(V); 1464 // If the value doesn't exist in the function map 1465 if (FVI == FI->second.map.end()) { 1466 // Look up the value in the module map. 1467 if (MI == mMap.end()) return -1; 1468 ValueMap::const_iterator MVI = MI->second.map.find(V); 1469 // If we didn't find it, it wasn't inserted 1470 if (MVI == MI->second.map.end()) return -1; 1471 assert(MVI != MI->second.map.end() && "Value not found"); 1472 // We found it only at the module level 1473 return MVI->second; 1474 1475 // else the value exists in the function map 1476 } else { 1477 // Return the slot number as the module's contribution to 1478 // the type plane plus the index in the function's contribution 1479 // to the type plane. 1480 if (MI != mMap.end()) 1481 return MI->second.next_slot + FVI->second; 1482 else 1483 return FVI->second; 1484 } 1485 } 1486 } 1487 1488 // N.B. Can get here only if either !TheFunction or the function doesn't 1489 // have a corresponding type plane for the Value 1490 1491 // Make sure the type plane exists 1492 if (MI == mMap.end()) return -1; 1493 // Lookup the value in the module's map 1494 ValueMap::const_iterator MVI = MI->second.map.find(V); 1495 // Make sure we found it. 1496 if (MVI == MI->second.map.end()) return -1; 1497 // Return it. 1498 return MVI->second; 1499} 1500 1501 1502// Create a new slot, or return the existing slot if it is already 1503// inserted. Note that the logic here parallels getSlot but instead 1504// of asserting when the Value* isn't found, it inserts the value. 1505unsigned SlotMachine::getOrCreateSlot(const Value *V) { 1506 const Type* VTy = V->getType(); 1507 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!"); 1508 assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 1509 "Can't insert a non-GlobalValue Constant into SlotMachine"); 1510 1511 // Look up the type plane for the Value's type from the module map 1512 TypedPlanes::const_iterator MI = mMap.find(VTy); 1513 1514 if (TheFunction) { 1515 // Get the type plane for the Value's type from the function map 1516 TypedPlanes::const_iterator FI = fMap.find(VTy); 1517 // If there is a corresponding type plane in the function map 1518 if (FI != fMap.end()) { 1519 // Lookup the Value in the function map 1520 ValueMap::const_iterator FVI = FI->second.map.find(V); 1521 // If the value doesn't exist in the function map 1522 if (FVI == FI->second.map.end()) { 1523 // If there is no corresponding type plane in the module map 1524 if (MI == mMap.end()) 1525 return insertValue(V); 1526 // Look up the value in the module map 1527 ValueMap::const_iterator MVI = MI->second.map.find(V); 1528 // If we didn't find it, it wasn't inserted 1529 if (MVI == MI->second.map.end()) 1530 return insertValue(V); 1531 else 1532 // We found it only at the module level 1533 return MVI->second; 1534 1535 // else the value exists in the function map 1536 } else { 1537 if (MI == mMap.end()) 1538 return FVI->second; 1539 else 1540 // Return the slot number as the module's contribution to 1541 // the type plane plus the index in the function's contribution 1542 // to the type plane. 1543 return MI->second.next_slot + FVI->second; 1544 } 1545 1546 // else there is not a corresponding type plane in the function map 1547 } else { 1548 // If the type plane doesn't exists at the module level 1549 if (MI == mMap.end()) { 1550 return insertValue(V); 1551 // else type plane exists at the module level, examine it 1552 } else { 1553 // Look up the value in the module's map 1554 ValueMap::const_iterator MVI = MI->second.map.find(V); 1555 // If we didn't find it there either 1556 if (MVI == MI->second.map.end()) 1557 // Return the slot number as the module's contribution to 1558 // the type plane plus the index of the function map insertion. 1559 return MI->second.next_slot + insertValue(V); 1560 else 1561 return MVI->second; 1562 } 1563 } 1564 } 1565 1566 // N.B. Can only get here if TheFunction == 0 1567 1568 // If the module map's type plane is not for the Value's type 1569 if (MI != mMap.end()) { 1570 // Lookup the value in the module's map 1571 ValueMap::const_iterator MVI = MI->second.map.find(V); 1572 if (MVI != MI->second.map.end()) 1573 return MVI->second; 1574 } 1575 1576 return insertValue(V); 1577} 1578 1579 1580// Low level insert function. Minimal checking is done. This 1581// function is just for the convenience of getOrCreateSlot (above). 1582unsigned SlotMachine::insertValue(const Value *V) { 1583 assert(V && "Can't insert a null Value into SlotMachine!"); 1584 assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 1585 "Can't insert a non-GlobalValue Constant into SlotMachine"); 1586 assert(V->getType() != Type::VoidTy && !V->hasName()); 1587 1588 const Type *VTy = V->getType(); 1589 unsigned DestSlot = 0; 1590 1591 if (TheFunction) { 1592 TypedPlanes::iterator I = fMap.find(VTy); 1593 if (I == fMap.end()) 1594 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first; 1595 DestSlot = I->second.map[V] = I->second.next_slot++; 1596 } else { 1597 TypedPlanes::iterator I = mMap.find(VTy); 1598 if (I == mMap.end()) 1599 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first; 1600 DestSlot = I->second.map[V] = I->second.next_slot++; 1601 } 1602 1603 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" << 1604 DestSlot << " ["); 1605 // G = Global, F = Function, o = other 1606 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 'o'))); 1607 SC_DEBUG("]\n"); 1608 return DestSlot; 1609} 1610