LLVM API Documentation
00001 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This library implements the functionality defined in llvm/Assembly/Writer.h 00011 // 00012 // Note that these routines must be extremely tolerant of various errors in the 00013 // LLVM code, because it can be used for debugging transformations. 00014 // 00015 //===----------------------------------------------------------------------===// 00016 00017 #include "llvm/Assembly/Writer.h" 00018 #include "llvm/Assembly/PrintModulePass.h" 00019 #include "llvm/Assembly/AsmAnnotationWriter.h" 00020 #include "llvm/CallingConv.h" 00021 #include "llvm/Constants.h" 00022 #include "llvm/DerivedTypes.h" 00023 #include "llvm/InlineAsm.h" 00024 #include "llvm/Instruction.h" 00025 #include "llvm/Instructions.h" 00026 #include "llvm/Operator.h" 00027 #include "llvm/Metadata.h" 00028 #include "llvm/Module.h" 00029 #include "llvm/ValueSymbolTable.h" 00030 #include "llvm/TypeSymbolTable.h" 00031 #include "llvm/ADT/DenseSet.h" 00032 #include "llvm/ADT/StringExtras.h" 00033 #include "llvm/ADT/STLExtras.h" 00034 #include "llvm/Support/CFG.h" 00035 #include "llvm/Support/ErrorHandling.h" 00036 #include "llvm/Support/MathExtras.h" 00037 #include "llvm/Support/FormattedStream.h" 00038 #include <algorithm> 00039 #include <cctype> 00040 #include <map> 00041 using namespace llvm; 00042 00043 // Make virtual table appear in this compilation unit. 00044 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {} 00045 00046 //===----------------------------------------------------------------------===// 00047 // Helper Functions 00048 //===----------------------------------------------------------------------===// 00049 00050 static const Module *getModuleFromVal(const Value *V) { 00051 if (const Argument *MA = dyn_cast<Argument>(V)) 00052 return MA->getParent() ? MA->getParent()->getParent() : 0; 00053 00054 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 00055 return BB->getParent() ? BB->getParent()->getParent() : 0; 00056 00057 if (const Instruction *I = dyn_cast<Instruction>(V)) { 00058 const Function *M = I->getParent() ? I->getParent()->getParent() : 0; 00059 return M ? M->getParent() : 0; 00060 } 00061 00062 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 00063 return GV->getParent(); 00064 return 0; 00065 } 00066 00067 // PrintEscapedString - Print each character of the specified string, escaping 00068 // it if it is not printable or if it is an escape char. 00069 static void PrintEscapedString(const StringRef &Name, 00070 raw_ostream &Out) { 00071 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 00072 unsigned char C = Name[i]; 00073 if (isprint(C) && C != '\\' && C != '"') 00074 Out << C; 00075 else 00076 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F); 00077 } 00078 } 00079 00080 enum PrefixType { 00081 GlobalPrefix, 00082 LabelPrefix, 00083 LocalPrefix, 00084 NoPrefix 00085 }; 00086 00087 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either 00088 /// prefixed with % (if the string only contains simple characters) or is 00089 /// surrounded with ""'s (if it has special chars in it). Print it out. 00090 static void PrintLLVMName(raw_ostream &OS, const StringRef &Name, 00091 PrefixType Prefix) { 00092 assert(Name.data() && "Cannot get empty name!"); 00093 switch (Prefix) { 00094 default: llvm_unreachable("Bad prefix!"); 00095 case NoPrefix: break; 00096 case GlobalPrefix: OS << '@'; break; 00097 case LabelPrefix: break; 00098 case LocalPrefix: OS << '%'; break; 00099 } 00100 00101 // Scan the name to see if it needs quotes first. 00102 bool NeedsQuotes = isdigit(Name[0]); 00103 if (!NeedsQuotes) { 00104 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 00105 char C = Name[i]; 00106 if (!isalnum(C) && C != '-' && C != '.' && C != '_') { 00107 NeedsQuotes = true; 00108 break; 00109 } 00110 } 00111 } 00112 00113 // If we didn't need any quotes, just write out the name in one blast. 00114 if (!NeedsQuotes) { 00115 OS << Name; 00116 return; 00117 } 00118 00119 // Okay, we need quotes. Output the quotes and escape any scary characters as 00120 // needed. 00121 OS << '"'; 00122 PrintEscapedString(Name, OS); 00123 OS << '"'; 00124 } 00125 00126 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either 00127 /// prefixed with % (if the string only contains simple characters) or is 00128 /// surrounded with ""'s (if it has special chars in it). Print it out. 00129 static void PrintLLVMName(raw_ostream &OS, const Value *V) { 00130 PrintLLVMName(OS, V->getName(), 00131 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix); 00132 } 00133 00134 //===----------------------------------------------------------------------===// 00135 // TypePrinting Class: Type printing machinery 00136 //===----------------------------------------------------------------------===// 00137 00138 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) { 00139 return *static_cast<DenseMap<const Type *, std::string>*>(M); 00140 } 00141 00142 void TypePrinting::clear() { 00143 getTypeNamesMap(TypeNames).clear(); 00144 } 00145 00146 bool TypePrinting::hasTypeName(const Type *Ty) const { 00147 return getTypeNamesMap(TypeNames).count(Ty); 00148 } 00149 00150 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) { 00151 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N)); 00152 } 00153 00154 00155 TypePrinting::TypePrinting() { 00156 TypeNames = new DenseMap<const Type *, std::string>(); 00157 } 00158 00159 TypePrinting::~TypePrinting() { 00160 delete &getTypeNamesMap(TypeNames); 00161 } 00162 00163 /// CalcTypeName - Write the specified type to the specified raw_ostream, making 00164 /// use of type names or up references to shorten the type name where possible. 00165 void TypePrinting::CalcTypeName(const Type *Ty, 00166 SmallVectorImpl<const Type *> &TypeStack, 00167 raw_ostream &OS, bool IgnoreTopLevelName) { 00168 // Check to see if the type is named. 00169 if (!IgnoreTopLevelName) { 00170 DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames); 00171 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty); 00172 if (I != TM.end()) { 00173 OS << I->second; 00174 return; 00175 } 00176 } 00177 00178 // Check to see if the Type is already on the stack... 00179 unsigned Slot = 0, CurSize = TypeStack.size(); 00180 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type 00181 00182 // This is another base case for the recursion. In this case, we know 00183 // that we have looped back to a type that we have previously visited. 00184 // Generate the appropriate upreference to handle this. 00185 if (Slot < CurSize) { 00186 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference 00187 return; 00188 } 00189 00190 TypeStack.push_back(Ty); // Recursive case: Add us to the stack.. 00191 00192 switch (Ty->getTypeID()) { 00193 case Type::VoidTyID: OS << "void"; break; 00194 case Type::FloatTyID: OS << "float"; break; 00195 case Type::DoubleTyID: OS << "double"; break; 00196 case Type::X86_FP80TyID: OS << "x86_fp80"; break; 00197 case Type::FP128TyID: OS << "fp128"; break; 00198 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break; 00199 case Type::LabelTyID: OS << "label"; break; 00200 case Type::MetadataTyID: OS << "metadata"; break; 00201 case Type::IntegerTyID: 00202 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth(); 00203 break; 00204 00205 case Type::FunctionTyID: { 00206 const FunctionType *FTy = cast<FunctionType>(Ty); 00207 CalcTypeName(FTy->getReturnType(), TypeStack, OS); 00208 OS << " ("; 00209 for (FunctionType::param_iterator I = FTy->param_begin(), 00210 E = FTy->param_end(); I != E; ++I) { 00211 if (I != FTy->param_begin()) 00212 OS << ", "; 00213 CalcTypeName(*I, TypeStack, OS); 00214 } 00215 if (FTy->isVarArg()) { 00216 if (FTy->getNumParams()) OS << ", "; 00217 OS << "..."; 00218 } 00219 OS << ')'; 00220 break; 00221 } 00222 case Type::StructTyID: { 00223 const StructType *STy = cast<StructType>(Ty); 00224 if (STy->isPacked()) 00225 OS << '<'; 00226 OS << "{ "; 00227 for (StructType::element_iterator I = STy->element_begin(), 00228 E = STy->element_end(); I != E; ++I) { 00229 CalcTypeName(*I, TypeStack, OS); 00230 if (next(I) != STy->element_end()) 00231 OS << ','; 00232 OS << ' '; 00233 } 00234 OS << '}'; 00235 if (STy->isPacked()) 00236 OS << '>'; 00237 break; 00238 } 00239 case Type::PointerTyID: { 00240 const PointerType *PTy = cast<PointerType>(Ty); 00241 CalcTypeName(PTy->getElementType(), TypeStack, OS); 00242 if (unsigned AddressSpace = PTy->getAddressSpace()) 00243 OS << " addrspace(" << AddressSpace << ')'; 00244 OS << '*'; 00245 break; 00246 } 00247 case Type::ArrayTyID: { 00248 const ArrayType *ATy = cast<ArrayType>(Ty); 00249 OS << '[' << ATy->getNumElements() << " x "; 00250 CalcTypeName(ATy->getElementType(), TypeStack, OS); 00251 OS << ']'; 00252 break; 00253 } 00254 case Type::VectorTyID: { 00255 const VectorType *PTy = cast<VectorType>(Ty); 00256 OS << "<" << PTy->getNumElements() << " x "; 00257 CalcTypeName(PTy->getElementType(), TypeStack, OS); 00258 OS << '>'; 00259 break; 00260 } 00261 case Type::OpaqueTyID: 00262 OS << "opaque"; 00263 break; 00264 default: 00265 OS << "<unrecognized-type>"; 00266 break; 00267 } 00268 00269 TypeStack.pop_back(); // Remove self from stack. 00270 } 00271 00272 /// printTypeInt - The internal guts of printing out a type that has a 00273 /// potentially named portion. 00274 /// 00275 void TypePrinting::print(const Type *Ty, raw_ostream &OS, 00276 bool IgnoreTopLevelName) { 00277 // Check to see if the type is named. 00278 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames); 00279 if (!IgnoreTopLevelName) { 00280 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty); 00281 if (I != TM.end()) { 00282 OS << I->second; 00283 return; 00284 } 00285 } 00286 00287 // Otherwise we have a type that has not been named but is a derived type. 00288 // Carefully recurse the type hierarchy to print out any contained symbolic 00289 // names. 00290 SmallVector<const Type *, 16> TypeStack; 00291 std::string TypeName; 00292 00293 raw_string_ostream TypeOS(TypeName); 00294 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName); 00295 OS << TypeOS.str(); 00296 00297 // Cache type name for later use. 00298 if (!IgnoreTopLevelName) 00299 TM.insert(std::make_pair(Ty, TypeOS.str())); 00300 } 00301 00302 namespace { 00303 class TypeFinder { 00304 // To avoid walking constant expressions multiple times and other IR 00305 // objects, we keep several helper maps. 00306 DenseSet<const Value*> VisitedConstants; 00307 DenseSet<const Type*> VisitedTypes; 00308 00309 TypePrinting &TP; 00310 std::vector<const Type*> &NumberedTypes; 00311 public: 00312 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes) 00313 : TP(tp), NumberedTypes(numberedTypes) {} 00314 00315 void Run(const Module &M) { 00316 // Get types from the type symbol table. This gets opaque types referened 00317 // only through derived named types. 00318 const TypeSymbolTable &ST = M.getTypeSymbolTable(); 00319 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end(); 00320 TI != E; ++TI) 00321 IncorporateType(TI->second); 00322 00323 // Get types from global variables. 00324 for (Module::const_global_iterator I = M.global_begin(), 00325 E = M.global_end(); I != E; ++I) { 00326 IncorporateType(I->getType()); 00327 if (I->hasInitializer()) 00328 IncorporateValue(I->getInitializer()); 00329 } 00330 00331 // Get types from aliases. 00332 for (Module::const_alias_iterator I = M.alias_begin(), 00333 E = M.alias_end(); I != E; ++I) { 00334 IncorporateType(I->getType()); 00335 IncorporateValue(I->getAliasee()); 00336 } 00337 00338 // Get types from functions. 00339 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) { 00340 IncorporateType(FI->getType()); 00341 00342 for (Function::const_iterator BB = FI->begin(), E = FI->end(); 00343 BB != E;++BB) 00344 for (BasicBlock::const_iterator II = BB->begin(), 00345 E = BB->end(); II != E; ++II) { 00346 const Instruction &I = *II; 00347 // Incorporate the type of the instruction and all its operands. 00348 IncorporateType(I.getType()); 00349 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end(); 00350 OI != OE; ++OI) 00351 IncorporateValue(*OI); 00352 } 00353 } 00354 } 00355 00356 private: 00357 void IncorporateType(const Type *Ty) { 00358 // Check to see if we're already visited this type. 00359 if (!VisitedTypes.insert(Ty).second) 00360 return; 00361 00362 // If this is a structure or opaque type, add a name for the type. 00363 if (((isa<StructType>(Ty) && cast<StructType>(Ty)->getNumElements()) 00364 || isa<OpaqueType>(Ty)) && !TP.hasTypeName(Ty)) { 00365 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size()))); 00366 NumberedTypes.push_back(Ty); 00367 } 00368 00369 // Recursively walk all contained types. 00370 for (Type::subtype_iterator I = Ty->subtype_begin(), 00371 E = Ty->subtype_end(); I != E; ++I) 00372 IncorporateType(*I); 00373 } 00374 00375 /// IncorporateValue - This method is used to walk operand lists finding 00376 /// types hiding in constant expressions and other operands that won't be 00377 /// walked in other ways. GlobalValues, basic blocks, instructions, and 00378 /// inst operands are all explicitly enumerated. 00379 void IncorporateValue(const Value *V) { 00380 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return; 00381 00382 // Already visited? 00383 if (!VisitedConstants.insert(V).second) 00384 return; 00385 00386 // Check this type. 00387 IncorporateType(V->getType()); 00388 00389 // Look in operands for types. 00390 const Constant *C = cast<Constant>(V); 00391 for (Constant::const_op_iterator I = C->op_begin(), 00392 E = C->op_end(); I != E;++I) 00393 IncorporateValue(*I); 00394 } 00395 }; 00396 } // end anonymous namespace 00397 00398 00399 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in 00400 /// the specified module to the TypePrinter and all numbered types to it and the 00401 /// NumberedTypes table. 00402 static void AddModuleTypesToPrinter(TypePrinting &TP, 00403 std::vector<const Type*> &NumberedTypes, 00404 const Module *M) { 00405 if (M == 0) return; 00406 00407 // If the module has a symbol table, take all global types and stuff their 00408 // names into the TypeNames map. 00409 const TypeSymbolTable &ST = M->getTypeSymbolTable(); 00410 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end(); 00411 TI != E; ++TI) { 00412 const Type *Ty = cast<Type>(TI->second); 00413 00414 // As a heuristic, don't insert pointer to primitive types, because 00415 // they are used too often to have a single useful name. 00416 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) { 00417 const Type *PETy = PTy->getElementType(); 00418 if ((PETy->isPrimitiveType() || PETy->isInteger()) && 00419 !isa<OpaqueType>(PETy)) 00420 continue; 00421 } 00422 00423 // Likewise don't insert primitives either. 00424 if (Ty->isInteger() || Ty->isPrimitiveType()) 00425 continue; 00426 00427 // Get the name as a string and insert it into TypeNames. 00428 std::string NameStr; 00429 raw_string_ostream NameROS(NameStr); 00430 formatted_raw_ostream NameOS(NameROS); 00431 PrintLLVMName(NameOS, TI->first, LocalPrefix); 00432 NameOS.flush(); 00433 TP.addTypeName(Ty, NameStr); 00434 } 00435 00436 // Walk the entire module to find references to unnamed structure and opaque 00437 // types. This is required for correctness by opaque types (because multiple 00438 // uses of an unnamed opaque type needs to be referred to by the same ID) and 00439 // it shrinks complex recursive structure types substantially in some cases. 00440 TypeFinder(TP, NumberedTypes).Run(*M); 00441 } 00442 00443 00444 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic 00445 /// type, iff there is an entry in the modules symbol table for the specified 00446 /// type or one of it's component types. 00447 /// 00448 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) { 00449 TypePrinting Printer; 00450 std::vector<const Type*> NumberedTypes; 00451 AddModuleTypesToPrinter(Printer, NumberedTypes, M); 00452 Printer.print(Ty, OS); 00453 } 00454 00455 //===----------------------------------------------------------------------===// 00456 // SlotTracker Class: Enumerate slot numbers for unnamed values 00457 //===----------------------------------------------------------------------===// 00458 00459 namespace { 00460 00461 /// This class provides computation of slot numbers for LLVM Assembly writing. 00462 /// 00463 class SlotTracker { 00464 public: 00465 /// ValueMap - A mapping of Values to slot numbers. 00466 typedef DenseMap<const Value*, unsigned> ValueMap; 00467 00468 private: 00469 /// TheModule - The module for which we are holding slot numbers. 00470 const Module* TheModule; 00471 00472 /// TheFunction - The function for which we are holding slot numbers. 00473 const Function* TheFunction; 00474 bool FunctionProcessed; 00475 00476 /// TheMDNode - The MDNode for which we are holding slot numbers. 00477 const MDNode *TheMDNode; 00478 00479 /// TheNamedMDNode - The MDNode for which we are holding slot numbers. 00480 const NamedMDNode *TheNamedMDNode; 00481 00482 /// mMap - The TypePlanes map for the module level data. 00483 ValueMap mMap; 00484 unsigned mNext; 00485 00486 /// fMap - The TypePlanes map for the function level data. 00487 ValueMap fMap; 00488 unsigned fNext; 00489 00490 /// mdnMap - Map for MDNodes. 00491 ValueMap mdnMap; 00492 unsigned mdnNext; 00493 public: 00494 /// Construct from a module 00495 explicit SlotTracker(const Module *M); 00496 /// Construct from a function, starting out in incorp state. 00497 explicit SlotTracker(const Function *F); 00498 /// Construct from a mdnode. 00499 explicit SlotTracker(const MDNode *N); 00500 /// Construct from a named mdnode. 00501 explicit SlotTracker(const NamedMDNode *N); 00502 00503 /// Return the slot number of the specified value in it's type 00504 /// plane. If something is not in the SlotTracker, return -1. 00505 int getLocalSlot(const Value *V); 00506 int getGlobalSlot(const GlobalValue *V); 00507 int getMetadataSlot(const MDNode *N); 00508 00509 /// If you'd like to deal with a function instead of just a module, use 00510 /// this method to get its data into the SlotTracker. 00511 void incorporateFunction(const Function *F) { 00512 TheFunction = F; 00513 FunctionProcessed = false; 00514 } 00515 00516 /// After calling incorporateFunction, use this method to remove the 00517 /// most recently incorporated function from the SlotTracker. This 00518 /// will reset the state of the machine back to just the module contents. 00519 void purgeFunction(); 00520 00521 /// MDNode map iterators. 00522 ValueMap::iterator mdnBegin() { return mdnMap.begin(); } 00523 ValueMap::iterator mdnEnd() { return mdnMap.end(); } 00524 unsigned mdnSize() const { return mdnMap.size(); } 00525 bool mdnEmpty() const { return mdnMap.empty(); } 00526 00527 /// This function does the actual initialization. 00528 inline void initialize(); 00529 00530 // Implementation Details 00531 private: 00532 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 00533 void CreateModuleSlot(const GlobalValue *V); 00534 00535 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table. 00536 void CreateMetadataSlot(const MDNode *N); 00537 00538 /// CreateFunctionSlot - Insert the specified Value* into the slot table. 00539 void CreateFunctionSlot(const Value *V); 00540 00541 /// Add all of the module level global variables (and their initializers) 00542 /// and function declarations, but not the contents of those functions. 00543 void processModule(); 00544 00545 /// Add all of the functions arguments, basic blocks, and instructions. 00546 void processFunction(); 00547 00548 /// Add all MDNode operands. 00549 void processMDNode(); 00550 00551 /// Add all MDNode operands. 00552 void processNamedMDNode(); 00553 00554 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT 00555 void operator=(const SlotTracker &); // DO NOT IMPLEMENT 00556 }; 00557 00558 } // end anonymous namespace 00559 00560 00561 static SlotTracker *createSlotTracker(const Value *V) { 00562 if (const Argument *FA = dyn_cast<Argument>(V)) 00563 return new SlotTracker(FA->getParent()); 00564 00565 if (const Instruction *I = dyn_cast<Instruction>(V)) 00566 return new SlotTracker(I->getParent()->getParent()); 00567 00568 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 00569 return new SlotTracker(BB->getParent()); 00570 00571 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) 00572 return new SlotTracker(GV->getParent()); 00573 00574 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 00575 return new SlotTracker(GA->getParent()); 00576 00577 if (const Function *Func = dyn_cast<Function>(V)) 00578 return new SlotTracker(Func); 00579 00580 return 0; 00581 } 00582 00583 #if 0 00584 #define ST_DEBUG(X) errs() << X 00585 #else 00586 #define ST_DEBUG(X) 00587 #endif 00588 00589 // Module level constructor. Causes the contents of the Module (sans functions) 00590 // to be added to the slot table. 00591 SlotTracker::SlotTracker(const Module *M) 00592 : TheModule(M), TheFunction(0), FunctionProcessed(false), TheMDNode(0), 00593 TheNamedMDNode(0), mNext(0), fNext(0), mdnNext(0) { 00594 } 00595 00596 // Function level constructor. Causes the contents of the Module and the one 00597 // function provided to be added to the slot table. 00598 SlotTracker::SlotTracker(const Function *F) 00599 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false), 00600 TheMDNode(0), TheNamedMDNode(0), mNext(0), fNext(0), mdnNext(0) { 00601 } 00602 00603 // Constructor to handle single MDNode. 00604 SlotTracker::SlotTracker(const MDNode *C) 00605 : TheModule(0), TheFunction(0), FunctionProcessed(false), TheMDNode(C), 00606 TheNamedMDNode(0), mNext(0), fNext(0), mdnNext(0) { 00607 } 00608 00609 // Constructor to handle single NamedMDNode. 00610 SlotTracker::SlotTracker(const NamedMDNode *N) 00611 : TheModule(0), TheFunction(0), FunctionProcessed(false), TheMDNode(0), 00612 TheNamedMDNode(N), mNext(0), fNext(0), mdnNext(0) { 00613 } 00614 00615 inline void SlotTracker::initialize() { 00616 if (TheModule) { 00617 processModule(); 00618 TheModule = 0; ///< Prevent re-processing next time we're called. 00619 } 00620 00621 if (TheFunction && !FunctionProcessed) 00622 processFunction(); 00623 00624 if (TheMDNode) 00625 processMDNode(); 00626 00627 if (TheNamedMDNode) 00628 processNamedMDNode(); 00629 } 00630 00631 // Iterate through all the global variables, functions, and global 00632 // variable initializers and create slots for them. 00633 void SlotTracker::processModule() { 00634 ST_DEBUG("begin processModule!\n"); 00635 00636 // Add all of the unnamed global variables to the value table. 00637 for (Module::const_global_iterator I = TheModule->global_begin(), 00638 E = TheModule->global_end(); I != E; ++I) { 00639 if (!I->hasName()) 00640 CreateModuleSlot(I); 00641 if (I->hasInitializer()) { 00642 if (MDNode *N = dyn_cast<MDNode>(I->getInitializer())) 00643 CreateMetadataSlot(N); 00644 } 00645 } 00646 00647 // Add metadata used by named metadata. 00648 for (Module::const_named_metadata_iterator 00649 I = TheModule->named_metadata_begin(), 00650 E = TheModule->named_metadata_end(); I != E; ++I) { 00651 const NamedMDNode *NMD = I; 00652 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) { 00653 MDNode *MD = dyn_cast_or_null<MDNode>(NMD->getElement(i)); 00654 if (MD) 00655 CreateMetadataSlot(MD); 00656 } 00657 } 00658 00659 // Add all the unnamed functions to the table. 00660 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 00661 I != E; ++I) 00662 if (!I->hasName()) 00663 CreateModuleSlot(I); 00664 00665 ST_DEBUG("end processModule!\n"); 00666 } 00667 00668 // Process the arguments, basic blocks, and instructions of a function. 00669 void SlotTracker::processFunction() { 00670 ST_DEBUG("begin processFunction!\n"); 00671 fNext = 0; 00672 00673 // Add all the function arguments with no names. 00674 for(Function::const_arg_iterator AI = TheFunction->arg_begin(), 00675 AE = TheFunction->arg_end(); AI != AE; ++AI) 00676 if (!AI->hasName()) 00677 CreateFunctionSlot(AI); 00678 00679 ST_DEBUG("Inserting Instructions:\n"); 00680 00681 // Add all of the basic blocks and instructions with no names. 00682 for (Function::const_iterator BB = TheFunction->begin(), 00683 E = TheFunction->end(); BB != E; ++BB) { 00684 if (!BB->hasName()) 00685 CreateFunctionSlot(BB); 00686 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; 00687 ++I) { 00688 if (I->getType() != Type::getVoidTy(TheFunction->getContext()) && 00689 !I->hasName()) 00690 CreateFunctionSlot(I); 00691 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 00692 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i))) 00693 CreateMetadataSlot(N); 00694 } 00695 } 00696 00697 FunctionProcessed = true; 00698 00699 ST_DEBUG("end processFunction!\n"); 00700 } 00701 00702 /// processMDNode - Process TheMDNode. 00703 void SlotTracker::processMDNode() { 00704 ST_DEBUG("begin processMDNode!\n"); 00705 mdnNext = 0; 00706 CreateMetadataSlot(TheMDNode); 00707 TheMDNode = 0; 00708 ST_DEBUG("end processMDNode!\n"); 00709 } 00710 00711 /// processNamedMDNode - Process TheNamedMDNode. 00712 void SlotTracker::processNamedMDNode() { 00713 ST_DEBUG("begin processNamedMDNode!\n"); 00714 mdnNext = 0; 00715 for (unsigned i = 0, e = TheNamedMDNode->getNumElements(); i != e; ++i) { 00716 MDNode *MD = dyn_cast_or_null<MDNode>(TheNamedMDNode->getElement(i)); 00717 if (MD) 00718 CreateMetadataSlot(MD); 00719 } 00720 TheNamedMDNode = 0; 00721 ST_DEBUG("end processNamedMDNode!\n"); 00722 } 00723 00724 /// Clean up after incorporating a function. This is the only way to get out of 00725 /// the function incorporation state that affects get*Slot/Create*Slot. Function 00726 /// incorporation state is indicated by TheFunction != 0. 00727 void SlotTracker::purgeFunction() { 00728 ST_DEBUG("begin purgeFunction!\n"); 00729 fMap.clear(); // Simply discard the function level map 00730 TheFunction = 0; 00731 FunctionProcessed = false; 00732 ST_DEBUG("end purgeFunction!\n"); 00733 } 00734 00735 /// getGlobalSlot - Get the slot number of a global value. 00736 int SlotTracker::getGlobalSlot(const GlobalValue *V) { 00737 // Check for uninitialized state and do lazy initialization. 00738 initialize(); 00739 00740 // Find the type plane in the module map 00741 ValueMap::iterator MI = mMap.find(V); 00742 return MI == mMap.end() ? -1 : (int)MI->second; 00743 } 00744 00745 /// getGlobalSlot - Get the slot number of a MDNode. 00746 int SlotTracker::getMetadataSlot(const MDNode *N) { 00747 // Check for uninitialized state and do lazy initialization. 00748 initialize(); 00749 00750 // Find the type plane in the module map 00751 ValueMap::iterator MI = mdnMap.find(N); 00752 return MI == mdnMap.end() ? -1 : (int)MI->second; 00753 } 00754 00755 00756 /// getLocalSlot - Get the slot number for a value that is local to a function. 00757 int SlotTracker::getLocalSlot(const Value *V) { 00758 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!"); 00759 00760 // Check for uninitialized state and do lazy initialization. 00761 initialize(); 00762 00763 ValueMap::iterator FI = fMap.find(V); 00764 return FI == fMap.end() ? -1 : (int)FI->second; 00765 } 00766 00767 00768 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 00769 void SlotTracker::CreateModuleSlot(const GlobalValue *V) { 00770 assert(V && "Can't insert a null Value into SlotTracker!"); 00771 assert(V->getType() != Type::getVoidTy(V->getContext()) && 00772 "Doesn't need a slot!"); 00773 assert(!V->hasName() && "Doesn't need a slot!"); 00774 00775 unsigned DestSlot = mNext++; 00776 mMap[V] = DestSlot; 00777 00778 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 00779 DestSlot << " ["); 00780 // G = Global, F = Function, A = Alias, o = other 00781 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' : 00782 (isa<Function>(V) ? 'F' : 00783 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n"); 00784 } 00785 00786 /// CreateSlot - Create a new slot for the specified value if it has no name. 00787 void SlotTracker::CreateFunctionSlot(const Value *V) { 00788 assert(V->getType() != Type::getVoidTy(TheFunction->getContext()) && 00789 !V->hasName() && "Doesn't need a slot!"); 00790 00791 unsigned DestSlot = fNext++; 00792 fMap[V] = DestSlot; 00793 00794 // G = Global, F = Function, o = other 00795 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 00796 DestSlot << " [o]\n"); 00797 } 00798 00799 /// CreateModuleSlot - Insert the specified MDNode* into the slot table. 00800 void SlotTracker::CreateMetadataSlot(const MDNode *N) { 00801 assert(N && "Can't insert a null Value into SlotTracker!"); 00802 00803 ValueMap::iterator I = mdnMap.find(N); 00804 if (I != mdnMap.end()) 00805 return; 00806 00807 unsigned DestSlot = mdnNext++; 00808 mdnMap[N] = DestSlot; 00809 00810 for (MDNode::const_elem_iterator MDI = N->elem_begin(), 00811 MDE = N->elem_end(); MDI != MDE; ++MDI) { 00812 const Value *TV = *MDI; 00813 if (TV) 00814 if (const MDNode *N2 = dyn_cast<MDNode>(TV)) 00815 CreateMetadataSlot(N2); 00816 } 00817 } 00818 00819 //===----------------------------------------------------------------------===// 00820 // AsmWriter Implementation 00821 //===----------------------------------------------------------------------===// 00822 00823 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 00824 TypePrinting *TypePrinter, 00825 SlotTracker *Machine); 00826 00827 00828 00829 static const char *getPredicateText(unsigned predicate) { 00830 const char * pred = "unknown"; 00831 switch (predicate) { 00832 case FCmpInst::FCMP_FALSE: pred = "false"; break; 00833 case FCmpInst::FCMP_OEQ: pred = "oeq"; break; 00834 case FCmpInst::FCMP_OGT: pred = "ogt"; break; 00835 case FCmpInst::FCMP_OGE: pred = "oge"; break; 00836 case FCmpInst::FCMP_OLT: pred = "olt"; break; 00837 case FCmpInst::FCMP_OLE: pred = "ole"; break; 00838 case FCmpInst::FCMP_ONE: pred = "one"; break; 00839 case FCmpInst::FCMP_ORD: pred = "ord"; break; 00840 case FCmpInst::FCMP_UNO: pred = "uno"; break; 00841 case FCmpInst::FCMP_UEQ: pred = "ueq"; break; 00842 case FCmpInst::FCMP_UGT: pred = "ugt"; break; 00843 case FCmpInst::FCMP_UGE: pred = "uge"; break; 00844 case FCmpInst::FCMP_ULT: pred = "ult"; break; 00845 case FCmpInst::FCMP_ULE: pred = "ule"; break; 00846 case FCmpInst::FCMP_UNE: pred = "une"; break; 00847 case FCmpInst::FCMP_TRUE: pred = "true"; break; 00848 case ICmpInst::ICMP_EQ: pred = "eq"; break; 00849 case ICmpInst::ICMP_NE: pred = "ne"; break; 00850 case ICmpInst::ICMP_SGT: pred = "sgt"; break; 00851 case ICmpInst::ICMP_SGE: pred = "sge"; break; 00852 case ICmpInst::ICMP_SLT: pred = "slt"; break; 00853 case ICmpInst::ICMP_SLE: pred = "sle"; break; 00854 case ICmpInst::ICMP_UGT: pred = "ugt"; break; 00855 case ICmpInst::ICMP_UGE: pred = "uge"; break; 00856 case ICmpInst::ICMP_ULT: pred = "ult"; break; 00857 case ICmpInst::ICMP_ULE: pred = "ule"; break; 00858 } 00859 return pred; 00860 } 00861 00862 static void WriteMDNodes(formatted_raw_ostream &Out, TypePrinting &TypePrinter, 00863 SlotTracker &Machine) { 00864 SmallVector<const MDNode *, 16> Nodes; 00865 Nodes.resize(Machine.mdnSize()); 00866 for (SlotTracker::ValueMap::iterator I = 00867 Machine.mdnBegin(), E = Machine.mdnEnd(); I != E; ++I) 00868 Nodes[I->second] = cast<MDNode>(I->first); 00869 00870 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { 00871 Out << '!' << i << " = metadata "; 00872 const MDNode *Node = Nodes[i]; 00873 Out << "!{"; 00874 for (MDNode::const_elem_iterator NI = Node->elem_begin(), 00875 NE = Node->elem_end(); NI != NE;) { 00876 const Value *V = *NI; 00877 if (!V) 00878 Out << "null"; 00879 else if (const MDNode *N = dyn_cast<MDNode>(V)) { 00880 Out << "metadata "; 00881 Out << '!' << Machine.getMetadataSlot(N); 00882 } 00883 else { 00884 TypePrinter.print((*NI)->getType(), Out); 00885 Out << ' '; 00886 WriteAsOperandInternal(Out, *NI, &TypePrinter, &Machine); 00887 } 00888 if (++NI != NE) 00889 Out << ", "; 00890 } 00891 Out << "}\n"; 00892 } 00893 } 00894 00895 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) { 00896 if (const OverflowingBinaryOperator *OBO = 00897 dyn_cast<OverflowingBinaryOperator>(U)) { 00898 if (OBO->hasNoUnsignedWrap()) 00899 Out << " nuw"; 00900 if (OBO->hasNoSignedWrap()) 00901 Out << " nsw"; 00902 } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) { 00903 if (Div->isExact()) 00904 Out << " exact"; 00905 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) { 00906 if (GEP->isInBounds()) 00907 Out << " inbounds"; 00908 } 00909 } 00910 00911 static void WriteConstantInt(raw_ostream &Out, const Constant *CV, 00912 TypePrinting &TypePrinter, SlotTracker *Machine) { 00913 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 00914 if (CI->getType() == Type::getInt1Ty(CV->getContext())) { 00915 Out << (CI->getZExtValue() ? "true" : "false"); 00916 return; 00917 } 00918 Out << CI->getValue(); 00919 return; 00920 } 00921 00922 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 00923 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble || 00924 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) { 00925 // We would like to output the FP constant value in exponential notation, 00926 // but we cannot do this if doing so will lose precision. Check here to 00927 // make sure that we only output it in exponential format if we can parse 00928 // the value back and get the same value. 00929 // 00930 bool ignored; 00931 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble; 00932 double Val = isDouble ? CFP->getValueAPF().convertToDouble() : 00933 CFP->getValueAPF().convertToFloat(); 00934 std::string StrVal = ftostr(CFP->getValueAPF()); 00935 00936 // Check to make sure that the stringized number is not some string like 00937 // "Inf" or NaN, that atof will accept, but the lexer will not. Check 00938 // that the string matches the "[-+]?[0-9]" regex. 00939 // 00940 if ((StrVal[0] >= '0' && StrVal[0] <= '9') || 00941 ((StrVal[0] == '-' || StrVal[0] == '+') && 00942 (StrVal[1] >= '0' && StrVal[1] <= '9'))) { 00943 // Reparse stringized version! 00944 if (atof(StrVal.c_str()) == Val) { 00945 Out << StrVal; 00946 return; 00947 } 00948 } 00949 // Otherwise we could not reparse it to exactly the same value, so we must 00950 // output the string in hexadecimal format! Note that loading and storing 00951 // floating point types changes the bits of NaNs on some hosts, notably 00952 // x86, so we must not use these types. 00953 assert(sizeof(double) == sizeof(uint64_t) && 00954 "assuming that double is 64 bits!"); 00955 char Buffer[40]; 00956 APFloat apf = CFP->getValueAPF(); 00957 // Floats are represented in ASCII IR as double, convert. 00958 if (!isDouble) 00959 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 00960 &ignored); 00961 Out << "0x" << 00962 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()), 00963 Buffer+40); 00964 return; 00965 } 00966 00967 // Some form of long double. These appear as a magic letter identifying 00968 // the type, then a fixed number of hex digits. 00969 Out << "0x"; 00970 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) { 00971 Out << 'K'; 00972 // api needed to prevent premature destruction 00973 APInt api = CFP->getValueAPF().bitcastToAPInt(); 00974 const uint64_t* p = api.getRawData(); 00975 uint64_t word = p[1]; 00976 int shiftcount=12; 00977 int width = api.getBitWidth(); 00978 for (int j=0; j<width; j+=4, shiftcount-=4) { 00979 unsigned int nibble = (word>>shiftcount) & 15; 00980 if (nibble < 10) 00981 Out << (unsigned char)(nibble + '0'); 00982 else 00983 Out << (unsigned char)(nibble - 10 + 'A'); 00984 if (shiftcount == 0 && j+4 < width) { 00985 word = *p; 00986 shiftcount = 64; 00987 if (width-j-4 < 64) 00988 shiftcount = width-j-4; 00989 } 00990 } 00991 return; 00992 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) 00993 Out << 'L'; 00994 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) 00995 Out << 'M'; 00996 else 00997 llvm_unreachable("Unsupported floating point type"); 00998 // api needed to prevent premature destruction 00999 APInt api = CFP->getValueAPF().bitcastToAPInt(); 01000 const uint64_t* p = api.getRawData(); 01001 uint64_t word = *p; 01002 int shiftcount=60; 01003 int width = api.getBitWidth(); 01004 for (int j=0; j<width; j+=4, shiftcount-=4) { 01005 unsigned int nibble = (word>>shiftcount) & 15; 01006 if (nibble < 10) 01007 Out << (unsigned char)(nibble + '0'); 01008 else 01009 Out << (unsigned char)(nibble - 10 + 'A'); 01010 if (shiftcount == 0 && j+4 < width) { 01011 word = *(++p); 01012 shiftcount = 64; 01013 if (width-j-4 < 64) 01014 shiftcount = width-j-4; 01015 } 01016 } 01017 return; 01018 } 01019 01020 if (isa<ConstantAggregateZero>(CV)) { 01021 Out << "zeroinitializer"; 01022 return; 01023 } 01024 01025 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) { 01026 // As a special case, print the array as a string if it is an array of 01027 // i8 with ConstantInt values. 01028 // 01029 const Type *ETy = CA->getType()->getElementType(); 01030 if (CA->isString()) { 01031 Out << "c\""; 01032 PrintEscapedString(CA->getAsString(), Out); 01033 Out << '"'; 01034 } else { // Cannot output in string format... 01035 Out << '['; 01036 if (CA->getNumOperands()) { 01037 TypePrinter.print(ETy, Out); 01038 Out << ' '; 01039 WriteAsOperandInternal(Out, CA->getOperand(0), 01040 &TypePrinter, Machine); 01041 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) { 01042 Out << ", "; 01043 TypePrinter.print(ETy, Out); 01044 Out << ' '; 01045 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine); 01046 } 01047 } 01048 Out << ']'; 01049 } 01050 return; 01051 } 01052 01053 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) { 01054 if (CS->getType()->isPacked()) 01055 Out << '<'; 01056 Out << '{'; 01057 unsigned N = CS->getNumOperands(); 01058 if (N) { 01059 Out << ' '; 01060 TypePrinter.print(CS->getOperand(0)->getType(), Out); 01061 Out << ' '; 01062 01063 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine); 01064 01065 for (unsigned i = 1; i < N; i++) { 01066 Out << ", "; 01067 TypePrinter.print(CS->getOperand(i)->getType(), Out); 01068 Out << ' '; 01069 01070 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine); 01071 } 01072 Out << ' '; 01073 } 01074 01075 Out << '}'; 01076 if (CS->getType()->isPacked()) 01077 Out << '>'; 01078 return; 01079 } 01080 01081 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) { 01082 const Type *ETy = CP->getType()->getElementType(); 01083 assert(CP->getNumOperands() > 0 && 01084 "Number of operands for a PackedConst must be > 0"); 01085 Out << '<'; 01086 TypePrinter.print(ETy, Out); 01087 Out << ' '; 01088 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine); 01089 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) { 01090 Out << ", "; 01091 TypePrinter.print(ETy, Out); 01092 Out << ' '; 01093 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine); 01094 } 01095 Out << '>'; 01096 return; 01097 } 01098 01099 if (isa<ConstantPointerNull>(CV)) { 01100 Out << "null"; 01101 return; 01102 } 01103 01104 if (isa<UndefValue>(CV)) { 01105 Out << "undef"; 01106 return; 01107 } 01108 01109 if (const MDNode *Node = dyn_cast<MDNode>(CV)) { 01110 Out << "!" << Machine->getMetadataSlot(Node); 01111 return; 01112 } 01113 01114 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 01115 Out << CE->getOpcodeName(); 01116 WriteOptimizationInfo(Out, CE); 01117 if (CE->isCompare()) 01118 Out << ' ' << getPredicateText(CE->getPredicate()); 01119 Out << " ("; 01120 01121 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) { 01122 TypePrinter.print((*OI)->getType(), Out); 01123 Out << ' '; 01124 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine); 01125 if (OI+1 != CE->op_end()) 01126 Out << ", "; 01127 } 01128 01129 if (CE->hasIndices()) { 01130 const SmallVector<unsigned, 4> &Indices = CE->getIndices(); 01131 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 01132 Out << ", " << Indices[i]; 01133 } 01134 01135 if (CE->isCast()) { 01136 Out << " to "; 01137 TypePrinter.print(CE->getType(), Out); 01138 } 01139 01140 Out << ')'; 01141 return; 01142 } 01143 01144 Out << "<placeholder or erroneous Constant>"; 01145 } 01146 01147 01148 /// WriteAsOperand - Write the name of the specified value out to the specified 01149 /// ostream. This can be useful when you just want to print int %reg126, not 01150 /// the whole instruction that generated it. 01151 /// 01152 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 01153 TypePrinting *TypePrinter, 01154 SlotTracker *Machine) { 01155 if (V->hasName()) { 01156 PrintLLVMName(Out, V); 01157 return; 01158 } 01159 01160 const Constant *CV = dyn_cast<Constant>(V); 01161 if (CV && !isa<GlobalValue>(CV)) { 01162 assert(TypePrinter && "Constants require TypePrinting!"); 01163 WriteConstantInt(Out, CV, *TypePrinter, Machine); 01164 return; 01165 } 01166 01167 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 01168 Out << "asm "; 01169 if (IA->hasSideEffects()) 01170 Out << "sideeffect "; 01171 Out << '"'; 01172 PrintEscapedString(IA->getAsmString(), Out); 01173 Out << "\", \""; 01174 PrintEscapedString(IA->getConstraintString(), Out); 01175 Out << '"'; 01176 return; 01177 } 01178 01179 if (const MDNode *N = dyn_cast<MDNode>(V)) { 01180 Out << '!' << Machine->getMetadataSlot(N); 01181 return; 01182 } 01183 01184 if (const MDString *MDS = dyn_cast<MDString>(V)) { 01185 Out << "!\""; 01186 PrintEscapedString(MDS->getString(), Out); 01187 Out << '"'; 01188 return; 01189 } 01190 01191 char Prefix = '%'; 01192 int Slot; 01193 if (Machine) { 01194 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 01195 Slot = Machine->getGlobalSlot(GV); 01196 Prefix = '@'; 01197 } else { 01198 Slot = Machine->getLocalSlot(V); 01199 } 01200 } else { 01201 Machine = createSlotTracker(V); 01202 if (Machine) { 01203 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 01204 Slot = Machine->getGlobalSlot(GV); 01205 Prefix = '@'; 01206 } else { 01207 Slot = Machine->getLocalSlot(V); 01208 } 01209 delete Machine; 01210 } else { 01211 Slot = -1; 01212 } 01213 } 01214 01215 if (Slot != -1) 01216 Out << Prefix << Slot; 01217 else 01218 Out << "<badref>"; 01219 } 01220 01221 /// WriteAsOperand - Write the name of the specified value out to the specified 01222 /// ostream. This can be useful when you just want to print int %reg126, not 01223 /// the whole instruction that generated it. 01224 /// 01225 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType, 01226 const Module *Context) { 01227 raw_os_ostream OS(Out); 01228 WriteAsOperand(OS, V, PrintType, Context); 01229 } 01230 01231 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, 01232 bool PrintType, const Module *Context) { 01233 01234 // Fast path: Don't construct and populate a TypePrinting object if we 01235 // won't be needing any types printed. 01236 if (!PrintType && 01237 (!isa<Constant>(V) || V->hasName() || isa<GlobalValue>(V))) { 01238 WriteAsOperandInternal(Out, V, 0, 0); 01239 return; 01240 } 01241 01242 if (Context == 0) Context = getModuleFromVal(V); 01243 01244 TypePrinting TypePrinter; 01245 std::vector<const Type*> NumberedTypes; 01246 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context); 01247 if (PrintType) { 01248 TypePrinter.print(V->getType(), Out); 01249 Out << ' '; 01250 } 01251 01252 WriteAsOperandInternal(Out, V, &TypePrinter, 0); 01253 } 01254 01255 namespace { 01256 01257 class AssemblyWriter { 01258 formatted_raw_ostream &Out; 01259 SlotTracker &Machine; 01260 const Module *TheModule; 01261 TypePrinting TypePrinter; 01262 AssemblyAnnotationWriter *AnnotationWriter; 01263 std::vector<const Type*> NumberedTypes; 01264 01265 // Each MDNode is assigned unique MetadataIDNo. 01266 std::map<const MDNode *, unsigned> MDNodes; 01267 unsigned MetadataIDNo; 01268 public: 01269 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 01270 const Module *M, 01271 AssemblyAnnotationWriter *AAW) 01272 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW), MetadataIDNo(0) { 01273 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M); 01274 } 01275 01276 void write(const Module *M) { printModule(M); } 01277 01278 void write(const GlobalValue *G) { 01279 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) 01280 printGlobal(GV); 01281 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G)) 01282 printAlias(GA); 01283 else if (const Function *F = dyn_cast<Function>(G)) 01284 printFunction(F); 01285 else 01286 llvm_unreachable("Unknown global"); 01287 } 01288 01289 void write(const BasicBlock *BB) { printBasicBlock(BB); } 01290 void write(const Instruction *I) { printInstruction(*I); } 01291 01292 void writeOperand(const Value *Op, bool PrintType); 01293 void writeParamOperand(const Value *Operand, Attributes Attrs); 01294 01295 const Module* getModule() { return TheModule; } 01296 01297 private: 01298 void printModule(const Module *M); 01299 void printTypeSymbolTable(const TypeSymbolTable &ST); 01300 void printGlobal(const GlobalVariable *GV); 01301 void printAlias(const GlobalAlias *GV); 01302 void printFunction(const Function *F); 01303 void printArgument(const Argument *FA, Attributes Attrs); 01304 void printBasicBlock(const BasicBlock *BB); 01305 void printInstruction(const Instruction &I); 01306 01307 // printInfoComment - Print a little comment after the instruction indicating 01308 // which slot it occupies. 01309 void printInfoComment(const Value &V); 01310 }; 01311 } // end of anonymous namespace 01312 01313 01314 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) { 01315 if (Operand == 0) { 01316 Out << "<null operand!>"; 01317 } else { 01318 if (PrintType) { 01319 TypePrinter.print(Operand->getType(), Out); 01320 Out << ' '; 01321 } 01322 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine); 01323 } 01324 } 01325 01326 void AssemblyWriter::writeParamOperand(const Value *Operand, 01327 Attributes Attrs) { 01328 if (Operand == 0) { 01329 Out << "<null operand!>"; 01330 } else { 01331 // Print the type 01332 TypePrinter.print(Operand->getType(), Out); 01333 // Print parameter attributes list 01334 if (Attrs != Attribute::None) 01335 Out << ' ' << Attribute::getAsString(Attrs); 01336 Out << ' '; 01337 // Print the operand 01338 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine); 01339 } 01340 } 01341 01342 void AssemblyWriter::printModule(const Module *M) { 01343 if (!M->getModuleIdentifier().empty() && 01344 // Don't print the ID if it will start a new line (which would 01345 // require a comment char before it). 01346 M->getModuleIdentifier().find('\n') == std::string::npos) 01347 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 01348 01349 if (!M->getDataLayout().empty()) 01350 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n"; 01351 if (!M->getTargetTriple().empty()) 01352 Out << "target triple = \"" << M->getTargetTriple() << "\"\n"; 01353 01354 if (!M->getModuleInlineAsm().empty()) { 01355 // Split the string into lines, to make it easier to read the .ll file. 01356 std::string Asm = M->getModuleInlineAsm(); 01357 size_t CurPos = 0; 01358 size_t NewLine = Asm.find_first_of('\n', CurPos); 01359 Out << '\n'; 01360 while (NewLine != std::string::npos) { 01361 // We found a newline, print the portion of the asm string from the 01362 // last newline up to this newline. 01363 Out << "module asm \""; 01364 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine), 01365 Out); 01366 Out << "\"\n"; 01367 CurPos = NewLine+1; 01368 NewLine = Asm.find_first_of('\n', CurPos); 01369 } 01370 Out << "module asm \""; 01371 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out); 01372 Out << "\"\n"; 01373 } 01374 01375 // Loop over the dependent libraries and emit them. 01376 Module::lib_iterator LI = M->lib_begin(); 01377 Module::lib_iterator LE = M->lib_end(); 01378 if (LI != LE) { 01379 Out << '\n'; 01380 Out << "deplibs = [ "; 01381 while (LI != LE) { 01382 Out << '"' << *LI << '"'; 01383 ++LI; 01384 if (LI != LE) 01385 Out << ", "; 01386 } 01387 Out << " ]"; 01388 } 01389 01390 // Loop over the symbol table, emitting all id'd types. 01391 if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n'; 01392 printTypeSymbolTable(M->getTypeSymbolTable()); 01393 01394 // Output all globals. 01395 if (!M->global_empty()) Out << '\n'; 01396 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); 01397 I != E; ++I) 01398 printGlobal(I); 01399 01400 // Output all aliases. 01401 if (!M->alias_empty()) Out << "\n"; 01402 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end(); 01403 I != E; ++I) 01404 printAlias(I); 01405 01406 // Output all of the functions. 01407 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) 01408 printFunction(I); 01409 01410 // Output named metadata. 01411 if (!M->named_metadata_empty()) Out << '\n'; 01412 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(), 01413 E = M->named_metadata_end(); I != E; ++I) { 01414 const NamedMDNode *NMD = I; 01415 Out << "!" << NMD->getName() << " = !{"; 01416 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) { 01417 if (i) Out << ", "; 01418 MDNode *MD = dyn_cast_or_null<MDNode>(NMD->getElement(i)); 01419 Out << '!' << Machine.getMetadataSlot(MD); 01420 } 01421 Out << "}\n"; 01422 } 01423 01424 // Output metadata. 01425 if (!Machine.mdnEmpty()) Out << '\n'; 01426 WriteMDNodes(Out, TypePrinter, Machine); 01427 } 01428 01429 static void PrintLinkage(GlobalValue::LinkageTypes LT, 01430 formatted_raw_ostream &Out) { 01431 switch (LT) { 01432 case GlobalValue::ExternalLinkage: break; 01433 case GlobalValue::PrivateLinkage: Out << "private "; break; 01434 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break; 01435 case GlobalValue::InternalLinkage: Out << "internal "; break; 01436 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break; 01437 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break; 01438 case GlobalValue::WeakAnyLinkage: Out << "weak "; break; 01439 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break; 01440 case GlobalValue::CommonLinkage: Out << "common "; break; 01441 case GlobalValue::AppendingLinkage: Out << "appending "; break; 01442 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break; 01443 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break; 01444 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break; 01445 case GlobalValue::AvailableExternallyLinkage: 01446 Out << "available_externally "; 01447 break; 01448 case GlobalValue::GhostLinkage: 01449 llvm_unreachable("GhostLinkage not allowed in AsmWriter!"); 01450 } 01451 } 01452 01453 01454 static void PrintVisibility(GlobalValue::VisibilityTypes Vis, 01455 formatted_raw_ostream &Out) { 01456 switch (Vis) { 01457 default: llvm_unreachable("Invalid visibility style!"); 01458 case GlobalValue::DefaultVisibility: break; 01459 case GlobalValue::HiddenVisibility: Out << "hidden "; break; 01460 case GlobalValue::ProtectedVisibility: Out << "protected "; break; 01461 } 01462 } 01463 01464 void AssemblyWriter::printGlobal(const GlobalVariable *GV) { 01465 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine); 01466 Out << " = "; 01467 01468 if (!GV->hasInitializer() && GV->hasExternalLinkage()) 01469 Out << "external "; 01470 01471 PrintLinkage(GV->getLinkage(), Out); 01472 PrintVisibility(GV->getVisibility(), Out); 01473 01474 if (GV->isThreadLocal()) Out << "thread_local "; 01475 if (unsigned AddressSpace = GV->getType()->getAddressSpace()) 01476 Out << "addrspace(" << AddressSpace << ") "; 01477 Out << (GV->isConstant() ? "constant " : "global "); 01478 TypePrinter.print(GV->getType()->getElementType(), Out); 01479 01480 if (GV->hasInitializer()) { 01481 Out << ' '; 01482 writeOperand(GV->getInitializer(), false); 01483 } 01484 01485 if (GV->hasSection()) 01486 Out << ", section \"" << GV->getSection() << '"'; 01487 if (GV->getAlignment()) 01488 Out << ", align " << GV->getAlignment(); 01489 01490 printInfoComment(*GV); 01491 Out << '\n'; 01492 } 01493 01494 void AssemblyWriter::printAlias(const GlobalAlias *GA) { 01495 // Don't crash when dumping partially built GA 01496 if (!GA->hasName()) 01497 Out << "<<nameless>> = "; 01498 else { 01499 PrintLLVMName(Out, GA); 01500 Out << " = "; 01501 } 01502 PrintVisibility(GA->getVisibility(), Out); 01503 01504 Out << "alias "; 01505 01506 PrintLinkage(GA->getLinkage(), Out); 01507 01508 const Constant *Aliasee = GA->getAliasee(); 01509 01510 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) { 01511 TypePrinter.print(GV->getType(), Out); 01512 Out << ' '; 01513 PrintLLVMName(Out, GV); 01514 } else if (const Function *F = dyn_cast<Function>(Aliasee)) { 01515 TypePrinter.print(F->getFunctionType(), Out); 01516 Out << "* "; 01517 01518 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine); 01519 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) { 01520 TypePrinter.print(GA->getType(), Out); 01521 Out << ' '; 01522 PrintLLVMName(Out, GA); 01523 } else { 01524 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee); 01525 // The only valid GEP is an all zero GEP. 01526 assert((CE->getOpcode() == Instruction::BitCast || 01527 CE->getOpcode() == Instruction::GetElementPtr) && 01528 "Unsupported aliasee"); 01529 writeOperand(CE, false); 01530 } 01531 01532 printInfoComment(*GA); 01533 Out << '\n'; 01534 } 01535 01536 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) { 01537 // Emit all numbered types. 01538 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) { 01539 Out << '%' << i << " = type "; 01540 01541 // Make sure we print out at least one level of the type structure, so 01542 // that we do not get %2 = type %2 01543 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out); 01544 Out << '\n'; 01545 } 01546 01547 // Print the named types. 01548 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end(); 01549 TI != TE; ++TI) { 01550 PrintLLVMName(Out, TI->first, LocalPrefix); 01551 Out << " = type "; 01552 01553 // Make sure we print out at least one level of the type structure, so 01554 // that we do not get %FILE = type %FILE 01555 TypePrinter.printAtLeastOneLevel(TI->second, Out); 01556 Out << '\n'; 01557 } 01558 } 01559 01560 /// printFunction - Print all aspects of a function. 01561 /// 01562 void AssemblyWriter::printFunction(const Function *F) { 01563 // Print out the return type and name. 01564 Out << '\n'; 01565 01566 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out); 01567 01568 if (F->isDeclaration()) 01569 Out << "declare "; 01570 else 01571 Out << "define "; 01572 01573 PrintLinkage(F->getLinkage(), Out); 01574 PrintVisibility(F->getVisibility(), Out); 01575 01576 // Print the calling convention. 01577 switch (F->getCallingConv()) { 01578 case CallingConv::C: break; // default 01579 case CallingConv::Fast: Out << "fastcc "; break; 01580 case CallingConv::Cold: Out << "coldcc "; break; 01581 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break; 01582 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 01583 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break; 01584 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break; 01585 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break; 01586 default: Out << "cc" << F->getCallingConv() << " "; break; 01587 } 01588 01589 const FunctionType *FT = F->getFunctionType(); 01590 const AttrListPtr &Attrs = F->getAttributes(); 01591 Attributes RetAttrs = Attrs.getRetAttributes(); 01592 if (RetAttrs != Attribute::None) 01593 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' '; 01594 TypePrinter.print(F->getReturnType(), Out); 01595 Out << ' '; 01596 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine); 01597 Out << '('; 01598 Machine.incorporateFunction(F); 01599 01600 // Loop over the arguments, printing them... 01601 01602 unsigned Idx = 1; 01603 if (!F->isDeclaration()) { 01604 // If this isn't a declaration, print the argument names as well. 01605 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 01606 I != E; ++I) { 01607 // Insert commas as we go... the first arg doesn't get a comma 01608 if (I != F->arg_begin()) Out << ", "; 01609 printArgument(I, Attrs.getParamAttributes(Idx)); 01610 Idx++; 01611 } 01612 } else { 01613 // Otherwise, print the types from the function type. 01614 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 01615 // Insert commas as we go... the first arg doesn't get a comma 01616 if (i) Out << ", "; 01617 01618 // Output type... 01619 TypePrinter.print(FT->getParamType(i), Out); 01620 01621 Attributes ArgAttrs = Attrs.getParamAttributes(i+1); 01622 if (ArgAttrs != Attribute::None) 01623 Out << ' ' << Attribute::getAsString(ArgAttrs); 01624 } 01625 } 01626 01627 // Finish printing arguments... 01628 if (FT->isVarArg()) { 01629 if (FT->getNumParams()) Out << ", "; 01630 Out << "..."; // Output varargs portion of signature! 01631 } 01632 Out << ')'; 01633 Attributes FnAttrs = Attrs.getFnAttributes(); 01634 if (FnAttrs != Attribute::None) 01635 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes()); 01636 if (F->hasSection()) 01637 Out << " section \"" << F->getSection() << '"'; 01638 if (F->getAlignment()) 01639 Out << " align " << F->getAlignment(); 01640 if (F->hasGC()) 01641 Out << " gc \"" << F->getGC() << '"'; 01642 if (F->isDeclaration()) { 01643 Out << "\n"; 01644 } else { 01645 Out << " {"; 01646 01647 // Output all of its basic blocks... for the function 01648 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I) 01649 printBasicBlock(I); 01650 01651 Out << "}\n"; 01652 } 01653 01654 Machine.purgeFunction(); 01655 } 01656 01657 /// printArgument - This member is called for every argument that is passed into 01658 /// the function. Simply print it out 01659 /// 01660 void AssemblyWriter::printArgument(const Argument *Arg, 01661 Attributes Attrs) { 01662 // Output type... 01663 TypePrinter.print(Arg->getType(), Out); 01664 01665 // Output parameter attributes list 01666 if (Attrs != Attribute::None) 01667 Out << ' ' << Attribute::getAsString(Attrs); 01668 01669 // Output name, if available... 01670 if (Arg->hasName()) { 01671 Out << ' '; 01672 PrintLLVMName(Out, Arg); 01673 } 01674 } 01675 01676 /// printBasicBlock - This member is called for each basic block in a method. 01677 /// 01678 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { 01679 if (BB->hasName()) { // Print out the label if it exists... 01680 Out << "\n"; 01681 PrintLLVMName(Out, BB->getName(), LabelPrefix); 01682 Out << ':'; 01683 } else if (!BB->use_empty()) { // Don't print block # of no uses... 01684 Out << "\n; <label>:"; 01685 int Slot = Machine.getLocalSlot(BB); 01686 if (Slot != -1) 01687 Out << Slot; 01688 else 01689 Out << "<badref>"; 01690 } 01691 01692 if (BB->getParent() == 0) { 01693 Out.PadToColumn(50); 01694 Out << "; Error: Block without parent!"; 01695 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block? 01696 // Output predecessors for the block... 01697 Out.PadToColumn(50); 01698 Out << ";"; 01699 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB); 01700 01701 if (PI == PE) { 01702 Out << " No predecessors!"; 01703 } else { 01704 Out << " preds = "; 01705 writeOperand(*PI, false); 01706 for (++PI; PI != PE; ++PI) { 01707 Out << ", "; 01708 writeOperand(*PI, false); 01709 } 01710 } 01711 } 01712 01713 Out << "\n"; 01714 01715 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out); 01716 01717 // Output all of the instructions in the basic block... 01718 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 01719 printInstruction(*I); 01720 Out << '\n'; 01721 } 01722 01723 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out); 01724 } 01725 01726 01727 /// printInfoComment - Print a little comment after the instruction indicating 01728 /// which slot it occupies. 01729 /// 01730 void AssemblyWriter::printInfoComment(const Value &V) { 01731 if (V.getType() != Type::getVoidTy(V.getContext())) { 01732 Out.PadToColumn(50); 01733 Out << "; <"; 01734 TypePrinter.print(V.getType(), Out); 01735 Out << "> [#uses=" << V.getNumUses() << ']'; // Output # uses 01736 } 01737 } 01738 01739 // This member is called for each Instruction in a function.. 01740 void AssemblyWriter::printInstruction(const Instruction &I) { 01741 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out); 01742 01743 // Print out indentation for an instruction. 01744 Out << " "; 01745 01746 // Print out name if it exists... 01747 if (I.hasName()) { 01748 PrintLLVMName(Out, &I); 01749 Out << " = "; 01750 } else if (I.getType() != Type::getVoidTy(I.getContext())) { 01751 // Print out the def slot taken. 01752 int SlotNum = Machine.getLocalSlot(&I); 01753 if (SlotNum == -1) 01754 Out << "<badref> = "; 01755 else 01756 Out << '%' << SlotNum << " = "; 01757 } 01758 01759 // If this is a volatile load or store, print out the volatile marker. 01760 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) || 01761 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) { 01762 Out << "volatile "; 01763 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) { 01764 // If this is a call, check if it's a tail call. 01765 Out << "tail "; 01766 } 01767 01768 // Print out the opcode... 01769 Out << I.getOpcodeName(); 01770 01771 // Print out optimization information. 01772 WriteOptimizationInfo(Out, &I); 01773 01774 // Print out the compare instruction predicates 01775 if (const CmpInst *CI = dyn_cast<CmpInst>(&I)) 01776 Out << ' ' << getPredicateText(CI->getPredicate()); 01777 01778 // Print out the type of the operands... 01779 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0; 01780 01781 // Special case conditional branches to swizzle the condition out to the front 01782 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) { 01783 BranchInst &BI(cast<BranchInst>(I)); 01784 Out << ' '; 01785 writeOperand(BI.getCondition(), true); 01786 Out << ", "; 01787 writeOperand(BI.getSuccessor(0), true); 01788 Out << ", "; 01789 writeOperand(BI.getSuccessor(1), true); 01790 01791 } else if (isa<SwitchInst>(I)) { 01792 // Special case switch statement to get formatting nice and correct... 01793 Out << ' '; 01794 writeOperand(Operand , true); 01795 Out << ", "; 01796 writeOperand(I.getOperand(1), true); 01797 Out << " ["; 01798 01799 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) { 01800 Out << "\n "; 01801 writeOperand(I.getOperand(op ), true); 01802 Out << ", "; 01803 writeOperand(I.getOperand(op+1), true); 01804 } 01805 Out << "\n ]"; 01806 } else if (isa<PHINode>(I)) { 01807 Out << ' '; 01808 TypePrinter.print(I.getType(), Out); 01809 Out << ' '; 01810 01811 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) { 01812 if (op) Out << ", "; 01813 Out << "[ "; 01814 writeOperand(I.getOperand(op ), false); Out << ", "; 01815 writeOperand(I.getOperand(op+1), false); Out << " ]"; 01816 } 01817 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) { 01818 Out << ' '; 01819 writeOperand(I.getOperand(0), true); 01820 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i) 01821 Out << ", " << *i; 01822 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) { 01823 Out << ' '; 01824 writeOperand(I.getOperand(0), true); Out << ", "; 01825 writeOperand(I.getOperand(1), true); 01826 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i) 01827 Out << ", " << *i; 01828 } else if (isa<ReturnInst>(I) && !Operand) { 01829 Out << " void"; 01830 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 01831 // Print the calling convention being used. 01832 switch (CI->getCallingConv()) { 01833 case CallingConv::C: break; // default 01834 case CallingConv::Fast: Out << " fastcc"; break; 01835 case CallingConv::Cold: Out << " coldcc"; break; 01836 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break; 01837 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break; 01838 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break; 01839 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break; 01840 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break; 01841 default: Out << " cc" << CI->getCallingConv(); break; 01842 } 01843 01844 const PointerType *PTy = cast<PointerType>(Operand->getType()); 01845 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 01846 const Type *RetTy = FTy->getReturnType(); 01847 const AttrListPtr &PAL = CI->getAttributes(); 01848 01849 if (PAL.getRetAttributes() != Attribute::None) 01850 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes()); 01851 01852 // If possible, print out the short form of the call instruction. We can 01853 // only do this if the first argument is a pointer to a nonvararg function, 01854 // and if the return type is not a pointer to a function. 01855 // 01856 Out << ' '; 01857 if (!FTy->isVarArg() && 01858 (!isa<PointerType>(RetTy) || 01859 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) { 01860 TypePrinter.print(RetTy, Out); 01861 Out << ' '; 01862 writeOperand(Operand, false); 01863 } else { 01864 writeOperand(Operand, true); 01865 } 01866 Out << '('; 01867 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) { 01868 if (op > 1) 01869 Out << ", "; 01870 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op)); 01871 } 01872 Out << ')'; 01873 if (PAL.getFnAttributes() != Attribute::None) 01874 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes()); 01875 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 01876 const PointerType *PTy = cast<PointerType>(Operand->getType()); 01877 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 01878 const Type *RetTy = FTy->getReturnType(); 01879 const AttrListPtr &PAL = II->getAttributes(); 01880 01881 // Print the calling convention being used. 01882 switch (II->getCallingConv()) { 01883 case CallingConv::C: break; // default 01884 case CallingConv::Fast: Out << " fastcc"; break; 01885 case CallingConv::Cold: Out << " coldcc"; break; 01886 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break; 01887 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break; 01888 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break; 01889 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break; 01890 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break; 01891 default: Out << " cc" << II->getCallingConv(); break; 01892 } 01893 01894 if (PAL.getRetAttributes() != Attribute::None) 01895 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes()); 01896 01897 // If possible, print out the short form of the invoke instruction. We can 01898 // only do this if the first argument is a pointer to a nonvararg function, 01899 // and if the return type is not a pointer to a function. 01900 // 01901 Out << ' '; 01902 if (!FTy->isVarArg() && 01903 (!isa<PointerType>(RetTy) || 01904 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) { 01905 TypePrinter.print(RetTy, Out); 01906 Out << ' '; 01907 writeOperand(Operand, false); 01908 } else { 01909 writeOperand(Operand, true); 01910 } 01911 Out << '('; 01912 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) { 01913 if (op > 3) 01914 Out << ", "; 01915 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2)); 01916 } 01917 01918 Out << ')'; 01919 if (PAL.getFnAttributes() != Attribute::None) 01920 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes()); 01921 01922 Out << "\n to "; 01923 writeOperand(II->getNormalDest(), true); 01924 Out << " unwind "; 01925 writeOperand(II->getUnwindDest(), true); 01926 01927 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) { 01928 Out << ' '; 01929 TypePrinter.print(AI->getType()->getElementType(), Out); 01930 if (!AI->getArraySize() || AI->isArrayAllocation()) { 01931 Out << ", "; 01932 writeOperand(AI->getArraySize(), true); 01933 } 01934 if (AI->getAlignment()) { 01935 Out << ", align " << AI->getAlignment(); 01936 } 01937 } else if (isa<CastInst>(I)) { 01938 if (Operand) { 01939 Out << ' '; 01940 writeOperand(Operand, true); // Work with broken code 01941 } 01942 Out << " to "; 01943 TypePrinter.print(I.getType(), Out); 01944 } else if (isa<VAArgInst>(I)) { 01945 if (Operand) { 01946 Out << ' '; 01947 writeOperand(Operand, true); // Work with broken code 01948 } 01949 Out << ", "; 01950 TypePrinter.print(I.getType(), Out); 01951 } else if (Operand) { // Print the normal way. 01952 01953 // PrintAllTypes - Instructions who have operands of all the same type 01954 // omit the type from all but the first operand. If the instruction has 01955 // different type operands (for example br), then they are all printed. 01956 bool PrintAllTypes = false; 01957 const Type *TheType = Operand->getType(); 01958 01959 // Select, Store and ShuffleVector always print all types. 01960 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) 01961 || isa<ReturnInst>(I)) { 01962 PrintAllTypes = true; 01963 } else { 01964 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) { 01965 Operand = I.getOperand(i); 01966 // note that Operand shouldn't be null, but the test helps make dump() 01967 // more tolerant of malformed IR 01968 if (Operand && Operand->getType() != TheType) { 01969 PrintAllTypes = true; // We have differing types! Print them all! 01970 break; 01971 } 01972 } 01973 } 01974 01975 if (!PrintAllTypes) { 01976 Out << ' '; 01977 TypePrinter.print(TheType, Out); 01978 } 01979 01980 Out << ' '; 01981 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) { 01982 if (i) Out << ", "; 01983 writeOperand(I.getOperand(i), PrintAllTypes); 01984 } 01985 } 01986 01987 // Print post operand alignment for load/store 01988 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) { 01989 Out << ", align " << cast<LoadInst>(I).getAlignment(); 01990 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) { 01991 Out << ", align " << cast<StoreInst>(I).getAlignment(); 01992 } 01993 01994 printInfoComment(I); 01995 } 01996 01997 01998 //===----------------------------------------------------------------------===// 01999 // External Interface declarations 02000 //===----------------------------------------------------------------------===// 02001 02002 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 02003 raw_os_ostream OS(o); 02004 print(OS, AAW); 02005 } 02006 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const { 02007 SlotTracker SlotTable(this); 02008 formatted_raw_ostream OS(ROS); 02009 AssemblyWriter W(OS, SlotTable, this, AAW); 02010 W.write(this); 02011 } 02012 02013 void Type::print(std::ostream &o) const { 02014 raw_os_ostream OS(o); 02015 print(OS); 02016 } 02017 02018 void Type::print(raw_ostream &OS) const { 02019 if (this == 0) { 02020 OS << "<null Type>"; 02021 return; 02022 } 02023 TypePrinting().print(this, OS); 02024 } 02025 02026 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const { 02027 if (this == 0) { 02028 ROS << "printing a <null> value\n"; 02029 return; 02030 } 02031 formatted_raw_ostream OS(ROS); 02032 if (const Instruction *I = dyn_cast<Instruction>(this)) { 02033 const Function *F = I->getParent() ? I->getParent()->getParent() : 0; 02034 SlotTracker SlotTable(F); 02035 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW); 02036 W.write(I); 02037 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) { 02038 SlotTracker SlotTable(BB->getParent()); 02039 AssemblyWriter W(OS, SlotTable, 02040 BB->getParent() ? BB->getParent()->getParent() : 0, AAW); 02041 W.write(BB); 02042 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) { 02043 SlotTracker SlotTable(GV->getParent()); 02044 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW); 02045 W.write(GV); 02046 } else if (const MDString *MDS = dyn_cast<MDString>(this)) { 02047 TypePrinting TypePrinter; 02048 TypePrinter.print(MDS->getType(), OS); 02049 OS << ' '; 02050 OS << "!\""; 02051 PrintEscapedString(MDS->getString(), OS); 02052 OS << '"'; 02053 } else if (const MDNode *N = dyn_cast<MDNode>(this)) { 02054 SlotTracker SlotTable(N); 02055 TypePrinting TypePrinter; 02056 SlotTable.initialize(); 02057 WriteMDNodes(OS, TypePrinter, SlotTable); 02058 } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(this)) { 02059 SlotTracker SlotTable(N); 02060 TypePrinting TypePrinter; 02061 SlotTable.initialize(); 02062 OS << "!" << N->getName() << " = !{"; 02063 for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) { 02064 if (i) OS << ", "; 02065 MDNode *MD = dyn_cast_or_null<MDNode>(N->getElement(i)); 02066 if (MD) 02067 OS << '!' << SlotTable.getMetadataSlot(MD); 02068 else 02069 OS << "null"; 02070 } 02071 OS << "}\n"; 02072 WriteMDNodes(OS, TypePrinter, SlotTable); 02073 } else if (const Constant *C = dyn_cast<Constant>(this)) { 02074 TypePrinting TypePrinter; 02075 TypePrinter.print(C->getType(), OS); 02076 OS << ' '; 02077 WriteConstantInt(OS, C, TypePrinter, 0); 02078 } else if (const Argument *A = dyn_cast<Argument>(this)) { 02079 WriteAsOperand(OS, this, true, 02080 A->getParent() ? A->getParent()->getParent() : 0); 02081 } else if (isa<InlineAsm>(this)) { 02082 WriteAsOperand(OS, this, true, 0); 02083 } else { 02084 llvm_unreachable("Unknown value to print out!"); 02085 } 02086 } 02087 02088 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const { 02089 raw_os_ostream OS(O); 02090 print(OS, AAW); 02091 } 02092 02093 // Value::dump - allow easy printing of Values from the debugger. 02094 void Value::dump() const { print(errs()); errs() << '\n'; } 02095 02096 // Type::dump - allow easy printing of Types from the debugger. 02097 // This one uses type names from the given context module 02098 void Type::dump(const Module *Context) const { 02099 WriteTypeSymbolic(errs(), this, Context); 02100 errs() << '\n'; 02101 } 02102 02103 // Type::dump - allow easy printing of Types from the debugger. 02104 void Type::dump() const { dump(0); } 02105 02106 // Module::dump() - Allow printing of Modules from the debugger. 02107 void Module::dump() const { print(errs(), 0); }