LLVM API Documentation
00001 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file was developed by the LLVM research group and is distributed under 00006 // the University of Illinois Open Source 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/CachedWriter.h" 00018 #include "llvm/Assembly/Writer.h" 00019 #include "llvm/Assembly/PrintModulePass.h" 00020 #include "llvm/Assembly/AsmAnnotationWriter.h" 00021 #include "llvm/CallingConv.h" 00022 #include "llvm/Constants.h" 00023 #include "llvm/DerivedTypes.h" 00024 #include "llvm/InlineAsm.h" 00025 #include "llvm/Instruction.h" 00026 #include "llvm/Instructions.h" 00027 #include "llvm/Module.h" 00028 #include "llvm/SymbolTable.h" 00029 #include "llvm/Support/CFG.h" 00030 #include "llvm/ADT/StringExtras.h" 00031 #include "llvm/ADT/STLExtras.h" 00032 #include "llvm/Support/MathExtras.h" 00033 #include <algorithm> 00034 using namespace llvm; 00035 00036 namespace llvm { 00037 00038 // Make virtual table appear in this compilation unit. 00039 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {} 00040 00041 /// This class provides computation of slot numbers for LLVM Assembly writing. 00042 /// @brief LLVM Assembly Writing Slot Computation. 00043 class SlotMachine { 00044 00045 /// @name Types 00046 /// @{ 00047 public: 00048 00049 /// @brief A mapping of Values to slot numbers 00050 typedef std::map<const Value*, unsigned> ValueMap; 00051 typedef std::map<const Type*, unsigned> TypeMap; 00052 00053 /// @brief A plane with next slot number and ValueMap 00054 struct ValuePlane { 00055 unsigned next_slot; ///< The next slot number to use 00056 ValueMap map; ///< The map of Value* -> unsigned 00057 ValuePlane() { next_slot = 0; } ///< Make sure we start at 0 00058 }; 00059 00060 struct TypePlane { 00061 unsigned next_slot; 00062 TypeMap map; 00063 TypePlane() { next_slot = 0; } 00064 void clear() { map.clear(); next_slot = 0; } 00065 }; 00066 00067 /// @brief The map of planes by Type 00068 typedef std::map<const Type*, ValuePlane> TypedPlanes; 00069 00070 /// @} 00071 /// @name Constructors 00072 /// @{ 00073 public: 00074 /// @brief Construct from a module 00075 SlotMachine(const Module *M ); 00076 00077 /// @brief Construct from a function, starting out in incorp state. 00078 SlotMachine(const Function *F ); 00079 00080 /// @} 00081 /// @name Accessors 00082 /// @{ 00083 public: 00084 /// Return the slot number of the specified value in it's type 00085 /// plane. Its an error to ask for something not in the SlotMachine. 00086 /// Its an error to ask for a Type* 00087 int getSlot(const Value *V); 00088 int getSlot(const Type*Ty); 00089 00090 /// Determine if a Value has a slot or not 00091 bool hasSlot(const Value* V); 00092 bool hasSlot(const Type* Ty); 00093 00094 /// @} 00095 /// @name Mutators 00096 /// @{ 00097 public: 00098 /// If you'd like to deal with a function instead of just a module, use 00099 /// this method to get its data into the SlotMachine. 00100 void incorporateFunction(const Function *F) { 00101 TheFunction = F; 00102 FunctionProcessed = false; 00103 } 00104 00105 /// After calling incorporateFunction, use this method to remove the 00106 /// most recently incorporated function from the SlotMachine. This 00107 /// will reset the state of the machine back to just the module contents. 00108 void purgeFunction(); 00109 00110 /// @} 00111 /// @name Implementation Details 00112 /// @{ 00113 private: 00114 /// This function does the actual initialization. 00115 inline void initialize(); 00116 00117 /// Values can be crammed into here at will. If they haven't 00118 /// been inserted already, they get inserted, otherwise they are ignored. 00119 /// Either way, the slot number for the Value* is returned. 00120 unsigned createSlot(const Value *V); 00121 unsigned createSlot(const Type* Ty); 00122 00123 /// Insert a value into the value table. Return the slot number 00124 /// that it now occupies. BadThings(TM) will happen if you insert a 00125 /// Value that's already been inserted. 00126 unsigned insertValue( const Value *V ); 00127 unsigned insertValue( const Type* Ty); 00128 00129 /// Add all of the module level global variables (and their initializers) 00130 /// and function declarations, but not the contents of those functions. 00131 void processModule(); 00132 00133 /// Add all of the functions arguments, basic blocks, and instructions 00134 void processFunction(); 00135 00136 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT 00137 void operator=(const SlotMachine &); // DO NOT IMPLEMENT 00138 00139 /// @} 00140 /// @name Data 00141 /// @{ 00142 public: 00143 00144 /// @brief The module for which we are holding slot numbers 00145 const Module* TheModule; 00146 00147 /// @brief The function for which we are holding slot numbers 00148 const Function* TheFunction; 00149 bool FunctionProcessed; 00150 00151 /// @brief The TypePlanes map for the module level data 00152 TypedPlanes mMap; 00153 TypePlane mTypes; 00154 00155 /// @brief The TypePlanes map for the function level data 00156 TypedPlanes fMap; 00157 TypePlane fTypes; 00158 00159 /// @} 00160 00161 }; 00162 00163 } // end namespace llvm 00164 00165 static RegisterPass<PrintModulePass> 00166 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization); 00167 static RegisterPass<PrintFunctionPass> 00168 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization); 00169 00170 static void WriteAsOperandInternal(std::ostream &Out, const Value *V, 00171 bool PrintName, 00172 std::map<const Type *, std::string> &TypeTable, 00173 SlotMachine *Machine); 00174 00175 static void WriteAsOperandInternal(std::ostream &Out, const Type *T, 00176 bool PrintName, 00177 std::map<const Type *, std::string> &TypeTable, 00178 SlotMachine *Machine); 00179 00180 static const Module *getModuleFromVal(const Value *V) { 00181 if (const Argument *MA = dyn_cast<Argument>(V)) 00182 return MA->getParent() ? MA->getParent()->getParent() : 0; 00183 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 00184 return BB->getParent() ? BB->getParent()->getParent() : 0; 00185 else if (const Instruction *I = dyn_cast<Instruction>(V)) { 00186 const Function *M = I->getParent() ? I->getParent()->getParent() : 0; 00187 return M ? M->getParent() : 0; 00188 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 00189 return GV->getParent(); 00190 return 0; 00191 } 00192 00193 static SlotMachine *createSlotMachine(const Value *V) { 00194 if (const Argument *FA = dyn_cast<Argument>(V)) { 00195 return new SlotMachine(FA->getParent()); 00196 } else if (const Instruction *I = dyn_cast<Instruction>(V)) { 00197 return new SlotMachine(I->getParent()->getParent()); 00198 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) { 00199 return new SlotMachine(BB->getParent()); 00200 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){ 00201 return new SlotMachine(GV->getParent()); 00202 } else if (const Function *Func = dyn_cast<Function>(V)) { 00203 return new SlotMachine(Func); 00204 } 00205 return 0; 00206 } 00207 00208 // getLLVMName - Turn the specified string into an 'LLVM name', which is either 00209 // prefixed with % (if the string only contains simple characters) or is 00210 // surrounded with ""'s (if it has special chars in it). 00211 static std::string getLLVMName(const std::string &Name, 00212 bool prefixName = true) { 00213 assert(!Name.empty() && "Cannot get empty name!"); 00214 00215 // First character cannot start with a number... 00216 if (Name[0] >= '0' && Name[0] <= '9') 00217 return "\"" + Name + "\""; 00218 00219 // Scan to see if we have any characters that are not on the "white list" 00220 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 00221 char C = Name[i]; 00222 assert(C != '"' && "Illegal character in LLVM value name!"); 00223 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') && 00224 C != '-' && C != '.' && C != '_') 00225 return "\"" + Name + "\""; 00226 } 00227 00228 // If we get here, then the identifier is legal to use as a "VarID". 00229 if (prefixName) 00230 return "%"+Name; 00231 else 00232 return Name; 00233 } 00234 00235 00236 /// fillTypeNameTable - If the module has a symbol table, take all global types 00237 /// and stuff their names into the TypeNames map. 00238 /// 00239 static void fillTypeNameTable(const Module *M, 00240 std::map<const Type *, std::string> &TypeNames) { 00241 if (!M) return; 00242 const SymbolTable &ST = M->getSymbolTable(); 00243 SymbolTable::type_const_iterator TI = ST.type_begin(); 00244 for (; TI != ST.type_end(); ++TI ) { 00245 // As a heuristic, don't insert pointer to primitive types, because 00246 // they are used too often to have a single useful name. 00247 // 00248 const Type *Ty = cast<Type>(TI->second); 00249 if (!isa<PointerType>(Ty) || 00250 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() || 00251 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType())) 00252 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first))); 00253 } 00254 } 00255 00256 00257 00258 static void calcTypeName(const Type *Ty, 00259 std::vector<const Type *> &TypeStack, 00260 std::map<const Type *, std::string> &TypeNames, 00261 std::string & Result){ 00262 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) { 00263 Result += Ty->getDescription(); // Base case 00264 return; 00265 } 00266 00267 // Check to see if the type is named. 00268 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty); 00269 if (I != TypeNames.end()) { 00270 Result += I->second; 00271 return; 00272 } 00273 00274 if (isa<OpaqueType>(Ty)) { 00275 Result += "opaque"; 00276 return; 00277 } 00278 00279 // Check to see if the Type is already on the stack... 00280 unsigned Slot = 0, CurSize = TypeStack.size(); 00281 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type 00282 00283 // This is another base case for the recursion. In this case, we know 00284 // that we have looped back to a type that we have previously visited. 00285 // Generate the appropriate upreference to handle this. 00286 if (Slot < CurSize) { 00287 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference 00288 return; 00289 } 00290 00291 TypeStack.push_back(Ty); // Recursive case: Add us to the stack.. 00292 00293 switch (Ty->getTypeID()) { 00294 case Type::FunctionTyID: { 00295 const FunctionType *FTy = cast<FunctionType>(Ty); 00296 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result); 00297 Result += " ("; 00298 for (FunctionType::param_iterator I = FTy->param_begin(), 00299 E = FTy->param_end(); I != E; ++I) { 00300 if (I != FTy->param_begin()) 00301 Result += ", "; 00302 calcTypeName(*I, TypeStack, TypeNames, Result); 00303 } 00304 if (FTy->isVarArg()) { 00305 if (FTy->getNumParams()) Result += ", "; 00306 Result += "..."; 00307 } 00308 Result += ")"; 00309 break; 00310 } 00311 case Type::StructTyID: { 00312 const StructType *STy = cast<StructType>(Ty); 00313 Result += "{ "; 00314 for (StructType::element_iterator I = STy->element_begin(), 00315 E = STy->element_end(); I != E; ++I) { 00316 if (I != STy->element_begin()) 00317 Result += ", "; 00318 calcTypeName(*I, TypeStack, TypeNames, Result); 00319 } 00320 Result += " }"; 00321 break; 00322 } 00323 case Type::PointerTyID: 00324 calcTypeName(cast<PointerType>(Ty)->getElementType(), 00325 TypeStack, TypeNames, Result); 00326 Result += "*"; 00327 break; 00328 case Type::ArrayTyID: { 00329 const ArrayType *ATy = cast<ArrayType>(Ty); 00330 Result += "[" + utostr(ATy->getNumElements()) + " x "; 00331 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result); 00332 Result += "]"; 00333 break; 00334 } 00335 case Type::PackedTyID: { 00336 const PackedType *PTy = cast<PackedType>(Ty); 00337 Result += "<" + utostr(PTy->getNumElements()) + " x "; 00338 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result); 00339 Result += ">"; 00340 break; 00341 } 00342 case Type::OpaqueTyID: 00343 Result += "opaque"; 00344 break; 00345 default: 00346 Result += "<unrecognized-type>"; 00347 } 00348 00349 TypeStack.pop_back(); // Remove self from stack... 00350 return; 00351 } 00352 00353 00354 /// printTypeInt - The internal guts of printing out a type that has a 00355 /// potentially named portion. 00356 /// 00357 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty, 00358 std::map<const Type *, std::string> &TypeNames) { 00359 // Primitive types always print out their description, regardless of whether 00360 // they have been named or not. 00361 // 00362 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) 00363 return Out << Ty->getDescription(); 00364 00365 // Check to see if the type is named. 00366 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty); 00367 if (I != TypeNames.end()) return Out << I->second; 00368 00369 // Otherwise we have a type that has not been named but is a derived type. 00370 // Carefully recurse the type hierarchy to print out any contained symbolic 00371 // names. 00372 // 00373 std::vector<const Type *> TypeStack; 00374 std::string TypeName; 00375 calcTypeName(Ty, TypeStack, TypeNames, TypeName); 00376 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use 00377 return (Out << TypeName); 00378 } 00379 00380 00381 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic 00382 /// type, iff there is an entry in the modules symbol table for the specified 00383 /// type or one of it's component types. This is slower than a simple x << Type 00384 /// 00385 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty, 00386 const Module *M) { 00387 Out << ' '; 00388 00389 // If they want us to print out a type, attempt to make it symbolic if there 00390 // is a symbol table in the module... 00391 if (M) { 00392 std::map<const Type *, std::string> TypeNames; 00393 fillTypeNameTable(M, TypeNames); 00394 00395 return printTypeInt(Out, Ty, TypeNames); 00396 } else { 00397 return Out << Ty->getDescription(); 00398 } 00399 } 00400 00401 // PrintEscapedString - Print each character of the specified string, escaping 00402 // it if it is not printable or if it is an escape char. 00403 static void PrintEscapedString(const std::string &Str, std::ostream &Out) { 00404 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 00405 unsigned char C = Str[i]; 00406 if (isprint(C) && C != '"' && C != '\\') { 00407 Out << C; 00408 } else { 00409 Out << '\\' 00410 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A')) 00411 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A')); 00412 } 00413 } 00414 } 00415 00416 /// @brief Internal constant writer. 00417 static void WriteConstantInt(std::ostream &Out, const Constant *CV, 00418 bool PrintName, 00419 std::map<const Type *, std::string> &TypeTable, 00420 SlotMachine *Machine) { 00421 const int IndentSize = 4; 00422 static std::string Indent = "\n"; 00423 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) { 00424 Out << (CB == ConstantBool::True ? "true" : "false"); 00425 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) { 00426 Out << CI->getValue(); 00427 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) { 00428 Out << CI->getValue(); 00429 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 00430 // We would like to output the FP constant value in exponential notation, 00431 // but we cannot do this if doing so will lose precision. Check here to 00432 // make sure that we only output it in exponential format if we can parse 00433 // the value back and get the same value. 00434 // 00435 std::string StrVal = ftostr(CFP->getValue()); 00436 00437 // Check to make sure that the stringized number is not some string like 00438 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that 00439 // the string matches the "[-+]?[0-9]" regex. 00440 // 00441 if ((StrVal[0] >= '0' && StrVal[0] <= '9') || 00442 ((StrVal[0] == '-' || StrVal[0] == '+') && 00443 (StrVal[1] >= '0' && StrVal[1] <= '9'))) 00444 // Reparse stringized version! 00445 if (atof(StrVal.c_str()) == CFP->getValue()) { 00446 Out << StrVal; 00447 return; 00448 } 00449 00450 // Otherwise we could not reparse it to exactly the same value, so we must 00451 // output the string in hexadecimal format! 00452 assert(sizeof(double) == sizeof(uint64_t) && 00453 "assuming that double is 64 bits!"); 00454 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue())); 00455 00456 } else if (isa<ConstantAggregateZero>(CV)) { 00457 Out << "zeroinitializer"; 00458 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) { 00459 // As a special case, print the array as a string if it is an array of 00460 // ubytes or an array of sbytes with positive values. 00461 // 00462 const Type *ETy = CA->getType()->getElementType(); 00463 if (CA->isString()) { 00464 Out << "c\""; 00465 PrintEscapedString(CA->getAsString(), Out); 00466 Out << "\""; 00467 00468 } else { // Cannot output in string format... 00469 Out << '['; 00470 if (CA->getNumOperands()) { 00471 Out << ' '; 00472 printTypeInt(Out, ETy, TypeTable); 00473 WriteAsOperandInternal(Out, CA->getOperand(0), 00474 PrintName, TypeTable, Machine); 00475 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) { 00476 Out << ", "; 00477 printTypeInt(Out, ETy, TypeTable); 00478 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName, 00479 TypeTable, Machine); 00480 } 00481 } 00482 Out << " ]"; 00483 } 00484 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) { 00485 Out << '{'; 00486 unsigned N = CS->getNumOperands(); 00487 if (N) { 00488 if (N > 2) { 00489 Indent += std::string(IndentSize, ' '); 00490 Out << Indent; 00491 } else { 00492 Out << ' '; 00493 } 00494 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable); 00495 00496 WriteAsOperandInternal(Out, CS->getOperand(0), 00497 PrintName, TypeTable, Machine); 00498 00499 for (unsigned i = 1; i < N; i++) { 00500 Out << ", "; 00501 if (N > 2) Out << Indent; 00502 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable); 00503 00504 WriteAsOperandInternal(Out, CS->getOperand(i), 00505 PrintName, TypeTable, Machine); 00506 } 00507 if (N > 2) Indent.resize(Indent.size() - IndentSize); 00508 } 00509 00510 Out << " }"; 00511 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) { 00512 const Type *ETy = CP->getType()->getElementType(); 00513 assert(CP->getNumOperands() > 0 && 00514 "Number of operands for a PackedConst must be > 0"); 00515 Out << '<'; 00516 Out << ' '; 00517 printTypeInt(Out, ETy, TypeTable); 00518 WriteAsOperandInternal(Out, CP->getOperand(0), 00519 PrintName, TypeTable, Machine); 00520 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) { 00521 Out << ", "; 00522 printTypeInt(Out, ETy, TypeTable); 00523 WriteAsOperandInternal(Out, CP->getOperand(i), PrintName, 00524 TypeTable, Machine); 00525 } 00526 Out << " >"; 00527 } else if (isa<ConstantPointerNull>(CV)) { 00528 Out << "null"; 00529 00530 } else if (isa<UndefValue>(CV)) { 00531 Out << "undef"; 00532 00533 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 00534 Out << CE->getOpcodeName() << " ("; 00535 00536 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) { 00537 printTypeInt(Out, (*OI)->getType(), TypeTable); 00538 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine); 00539 if (OI+1 != CE->op_end()) 00540 Out << ", "; 00541 } 00542 00543 if (CE->getOpcode() == Instruction::Cast) { 00544 Out << " to "; 00545 printTypeInt(Out, CE->getType(), TypeTable); 00546 } 00547 Out << ')'; 00548 00549 } else { 00550 Out << "<placeholder or erroneous Constant>"; 00551 } 00552 } 00553 00554 00555 /// WriteAsOperand - Write the name of the specified value out to the specified 00556 /// ostream. This can be useful when you just want to print int %reg126, not 00557 /// the whole instruction that generated it. 00558 /// 00559 static void WriteAsOperandInternal(std::ostream &Out, const Value *V, 00560 bool PrintName, 00561 std::map<const Type*, std::string> &TypeTable, 00562 SlotMachine *Machine) { 00563 Out << ' '; 00564 if ((PrintName || isa<GlobalValue>(V)) && V->hasName()) 00565 Out << getLLVMName(V->getName()); 00566 else { 00567 const Constant *CV = dyn_cast<Constant>(V); 00568 if (CV && !isa<GlobalValue>(CV)) { 00569 WriteConstantInt(Out, CV, PrintName, TypeTable, Machine); 00570 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 00571 Out << "asm "; 00572 if (IA->hasSideEffects()) 00573 Out << "sideeffect "; 00574 Out << '"'; 00575 PrintEscapedString(IA->getAsmString(), Out); 00576 Out << "\", \""; 00577 PrintEscapedString(IA->getConstraintString(), Out); 00578 Out << '"'; 00579 } else { 00580 int Slot; 00581 if (Machine) { 00582 Slot = Machine->getSlot(V); 00583 } else { 00584 Machine = createSlotMachine(V); 00585 if (Machine) 00586 Slot = Machine->getSlot(V); 00587 else 00588 Slot = -1; 00589 delete Machine; 00590 } 00591 if (Slot != -1) 00592 Out << '%' << Slot; 00593 else 00594 Out << "<badref>"; 00595 } 00596 } 00597 } 00598 00599 /// WriteAsOperand - Write the name of the specified value out to the specified 00600 /// ostream. This can be useful when you just want to print int %reg126, not 00601 /// the whole instruction that generated it. 00602 /// 00603 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V, 00604 bool PrintType, bool PrintName, 00605 const Module *Context) { 00606 std::map<const Type *, std::string> TypeNames; 00607 if (Context == 0) Context = getModuleFromVal(V); 00608 00609 if (Context) 00610 fillTypeNameTable(Context, TypeNames); 00611 00612 if (PrintType) 00613 printTypeInt(Out, V->getType(), TypeNames); 00614 00615 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0); 00616 return Out; 00617 } 00618 00619 /// WriteAsOperandInternal - Write the name of the specified value out to 00620 /// the specified ostream. This can be useful when you just want to print 00621 /// int %reg126, not the whole instruction that generated it. 00622 /// 00623 static void WriteAsOperandInternal(std::ostream &Out, const Type *T, 00624 bool PrintName, 00625 std::map<const Type*, std::string> &TypeTable, 00626 SlotMachine *Machine) { 00627 Out << ' '; 00628 int Slot; 00629 if (Machine) { 00630 Slot = Machine->getSlot(T); 00631 if (Slot != -1) 00632 Out << '%' << Slot; 00633 else 00634 Out << "<badref>"; 00635 } else { 00636 Out << T->getDescription(); 00637 } 00638 } 00639 00640 /// WriteAsOperand - Write the name of the specified value out to the specified 00641 /// ostream. This can be useful when you just want to print int %reg126, not 00642 /// the whole instruction that generated it. 00643 /// 00644 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Type *Ty, 00645 bool PrintType, bool PrintName, 00646 const Module *Context) { 00647 std::map<const Type *, std::string> TypeNames; 00648 assert(Context != 0 && "Can't write types as operand without module context"); 00649 00650 fillTypeNameTable(Context, TypeNames); 00651 00652 // if (PrintType) 00653 // printTypeInt(Out, V->getType(), TypeNames); 00654 00655 printTypeInt(Out, Ty, TypeNames); 00656 00657 WriteAsOperandInternal(Out, Ty, PrintName, TypeNames, 0); 00658 return Out; 00659 } 00660 00661 namespace llvm { 00662 00663 class AssemblyWriter { 00664 std::ostream &Out; 00665 SlotMachine &Machine; 00666 const Module *TheModule; 00667 std::map<const Type *, std::string> TypeNames; 00668 AssemblyAnnotationWriter *AnnotationWriter; 00669 public: 00670 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M, 00671 AssemblyAnnotationWriter *AAW) 00672 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) { 00673 00674 // If the module has a symbol table, take all global types and stuff their 00675 // names into the TypeNames map. 00676 // 00677 fillTypeNameTable(M, TypeNames); 00678 } 00679 00680 inline void write(const Module *M) { printModule(M); } 00681 inline void write(const GlobalVariable *G) { printGlobal(G); } 00682 inline void write(const Function *F) { printFunction(F); } 00683 inline void write(const BasicBlock *BB) { printBasicBlock(BB); } 00684 inline void write(const Instruction *I) { printInstruction(*I); } 00685 inline void write(const Constant *CPV) { printConstant(CPV); } 00686 inline void write(const Type *Ty) { printType(Ty); } 00687 00688 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true); 00689 00690 const Module* getModule() { return TheModule; } 00691 00692 private: 00693 void printModule(const Module *M); 00694 void printSymbolTable(const SymbolTable &ST); 00695 void printConstant(const Constant *CPV); 00696 void printGlobal(const GlobalVariable *GV); 00697 void printFunction(const Function *F); 00698 void printArgument(const Argument *FA); 00699 void printBasicBlock(const BasicBlock *BB); 00700 void printInstruction(const Instruction &I); 00701 00702 // printType - Go to extreme measures to attempt to print out a short, 00703 // symbolic version of a type name. 00704 // 00705 std::ostream &printType(const Type *Ty) { 00706 return printTypeInt(Out, Ty, TypeNames); 00707 } 00708 00709 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type 00710 // without considering any symbolic types that we may have equal to it. 00711 // 00712 std::ostream &printTypeAtLeastOneLevel(const Type *Ty); 00713 00714 // printInfoComment - Print a little comment after the instruction indicating 00715 // which slot it occupies. 00716 void printInfoComment(const Value &V); 00717 }; 00718 } // end of llvm namespace 00719 00720 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type 00721 /// without considering any symbolic types that we may have equal to it. 00722 /// 00723 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) { 00724 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) { 00725 printType(FTy->getReturnType()) << " ("; 00726 for (FunctionType::param_iterator I = FTy->param_begin(), 00727 E = FTy->param_end(); I != E; ++I) { 00728 if (I != FTy->param_begin()) 00729 Out << ", "; 00730 printType(*I); 00731 } 00732 if (FTy->isVarArg()) { 00733 if (FTy->getNumParams()) Out << ", "; 00734 Out << "..."; 00735 } 00736 Out << ')'; 00737 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) { 00738 Out << "{ "; 00739 for (StructType::element_iterator I = STy->element_begin(), 00740 E = STy->element_end(); I != E; ++I) { 00741 if (I != STy->element_begin()) 00742 Out << ", "; 00743 printType(*I); 00744 } 00745 Out << " }"; 00746 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) { 00747 printType(PTy->getElementType()) << '*'; 00748 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 00749 Out << '[' << ATy->getNumElements() << " x "; 00750 printType(ATy->getElementType()) << ']'; 00751 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) { 00752 Out << '<' << PTy->getNumElements() << " x "; 00753 printType(PTy->getElementType()) << '>'; 00754 } 00755 else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) { 00756 Out << "opaque"; 00757 } else { 00758 if (!Ty->isPrimitiveType()) 00759 Out << "<unknown derived type>"; 00760 printType(Ty); 00761 } 00762 return Out; 00763 } 00764 00765 00766 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType, 00767 bool PrintName) { 00768 if (Operand != 0) { 00769 if (PrintType) { Out << ' '; printType(Operand->getType()); } 00770 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Machine); 00771 } else { 00772 Out << "<null operand!>"; 00773 } 00774 } 00775 00776 00777 void AssemblyWriter::printModule(const Module *M) { 00778 if (!M->getModuleIdentifier().empty() && 00779 // Don't print the ID if it will start a new line (which would 00780 // require a comment char before it). 00781 M->getModuleIdentifier().find('\n') == std::string::npos) 00782 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 00783 00784 switch (M->getEndianness()) { 00785 case Module::LittleEndian: Out << "target endian = little\n"; break; 00786 case Module::BigEndian: Out << "target endian = big\n"; break; 00787 case Module::AnyEndianness: break; 00788 } 00789 switch (M->getPointerSize()) { 00790 case Module::Pointer32: Out << "target pointersize = 32\n"; break; 00791 case Module::Pointer64: Out << "target pointersize = 64\n"; break; 00792 case Module::AnyPointerSize: break; 00793 } 00794 if (!M->getTargetTriple().empty()) 00795 Out << "target triple = \"" << M->getTargetTriple() << "\"\n"; 00796 00797 if (!M->getModuleInlineAsm().empty()) { 00798 // Split the string into lines, to make it easier to read the .ll file. 00799 std::string Asm = M->getModuleInlineAsm(); 00800 size_t CurPos = 0; 00801 size_t NewLine = Asm.find_first_of('\n', CurPos); 00802 while (NewLine != std::string::npos) { 00803 // We found a newline, print the portion of the asm string from the 00804 // last newline up to this newline. 00805 Out << "module asm \""; 00806 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine), 00807 Out); 00808 Out << "\"\n"; 00809 CurPos = NewLine+1; 00810 NewLine = Asm.find_first_of('\n', CurPos); 00811 } 00812 Out << "module asm \""; 00813 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out); 00814 Out << "\"\n"; 00815 } 00816 00817 // Loop over the dependent libraries and emit them. 00818 Module::lib_iterator LI = M->lib_begin(); 00819 Module::lib_iterator LE = M->lib_end(); 00820 if (LI != LE) { 00821 Out << "deplibs = [ "; 00822 while (LI != LE) { 00823 Out << '"' << *LI << '"'; 00824 ++LI; 00825 if (LI != LE) 00826 Out << ", "; 00827 } 00828 Out << " ]\n"; 00829 } 00830 00831 // Loop over the symbol table, emitting all named constants. 00832 printSymbolTable(M->getSymbolTable()); 00833 00834 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I) 00835 printGlobal(I); 00836 00837 Out << "\nimplementation ; Functions:\n"; 00838 00839 // Output all of the functions. 00840 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) 00841 printFunction(I); 00842 } 00843 00844 void AssemblyWriter::printGlobal(const GlobalVariable *GV) { 00845 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = "; 00846 00847 if (!GV->hasInitializer()) 00848 Out << "external "; 00849 else 00850 switch (GV->getLinkage()) { 00851 case GlobalValue::InternalLinkage: Out << "internal "; break; 00852 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break; 00853 case GlobalValue::WeakLinkage: Out << "weak "; break; 00854 case GlobalValue::AppendingLinkage: Out << "appending "; break; 00855 case GlobalValue::ExternalLinkage: break; 00856 case GlobalValue::GhostLinkage: 00857 std::cerr << "GhostLinkage not allowed in AsmWriter!\n"; 00858 abort(); 00859 } 00860 00861 Out << (GV->isConstant() ? "constant " : "global "); 00862 printType(GV->getType()->getElementType()); 00863 00864 if (GV->hasInitializer()) { 00865 Constant* C = cast<Constant>(GV->getInitializer()); 00866 assert(C && "GlobalVar initializer isn't constant?"); 00867 writeOperand(GV->getInitializer(), false, isa<GlobalValue>(C)); 00868 } 00869 00870 if (GV->hasSection()) 00871 Out << ", section \"" << GV->getSection() << '"'; 00872 if (GV->getAlignment()) 00873 Out << ", align " << GV->getAlignment(); 00874 00875 printInfoComment(*GV); 00876 Out << "\n"; 00877 } 00878 00879 00880 // printSymbolTable - Run through symbol table looking for constants 00881 // and types. Emit their declarations. 00882 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) { 00883 00884 // Print the types. 00885 for (SymbolTable::type_const_iterator TI = ST.type_begin(); 00886 TI != ST.type_end(); ++TI ) { 00887 Out << "\t" << getLLVMName(TI->first) << " = type "; 00888 00889 // Make sure we print out at least one level of the type structure, so 00890 // that we do not get %FILE = type %FILE 00891 // 00892 printTypeAtLeastOneLevel(TI->second) << "\n"; 00893 } 00894 00895 // Print the constants, in type plane order. 00896 for (SymbolTable::plane_const_iterator PI = ST.plane_begin(); 00897 PI != ST.plane_end(); ++PI ) { 00898 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first); 00899 SymbolTable::value_const_iterator VE = ST.value_end(PI->first); 00900 00901 for (; VI != VE; ++VI) { 00902 const Value* V = VI->second; 00903 const Constant *CPV = dyn_cast<Constant>(V) ; 00904 if (CPV && !isa<GlobalValue>(V)) { 00905 printConstant(CPV); 00906 } 00907 } 00908 } 00909 } 00910 00911 00912 /// printConstant - Print out a constant pool entry... 00913 /// 00914 void AssemblyWriter::printConstant(const Constant *CPV) { 00915 // Don't print out unnamed constants, they will be inlined 00916 if (!CPV->hasName()) return; 00917 00918 // Print out name... 00919 Out << "\t" << getLLVMName(CPV->getName()) << " ="; 00920 00921 // Write the value out now... 00922 writeOperand(CPV, true, false); 00923 00924 printInfoComment(*CPV); 00925 Out << "\n"; 00926 } 00927 00928 /// printFunction - Print all aspects of a function. 00929 /// 00930 void AssemblyWriter::printFunction(const Function *F) { 00931 // Print out the return type and name... 00932 Out << "\n"; 00933 00934 // Ensure that no local symbols conflict with global symbols. 00935 const_cast<Function*>(F)->renameLocalSymbols(); 00936 00937 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out); 00938 00939 if (F->isExternal()) 00940 Out << "declare "; 00941 else 00942 switch (F->getLinkage()) { 00943 case GlobalValue::InternalLinkage: Out << "internal "; break; 00944 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break; 00945 case GlobalValue::WeakLinkage: Out << "weak "; break; 00946 case GlobalValue::AppendingLinkage: Out << "appending "; break; 00947 case GlobalValue::ExternalLinkage: break; 00948 case GlobalValue::GhostLinkage: 00949 std::cerr << "GhostLinkage not allowed in AsmWriter!\n"; 00950 abort(); 00951 } 00952 00953 // Print the calling convention. 00954 switch (F->getCallingConv()) { 00955 case CallingConv::C: break; // default 00956 case CallingConv::CSRet: Out << "csretcc "; break; 00957 case CallingConv::Fast: Out << "fastcc "; break; 00958 case CallingConv::Cold: Out << "coldcc "; break; 00959 default: Out << "cc" << F->getCallingConv() << " "; break; 00960 } 00961 00962 printType(F->getReturnType()) << ' '; 00963 if (!F->getName().empty()) 00964 Out << getLLVMName(F->getName()); 00965 else 00966 Out << "\"\""; 00967 Out << '('; 00968 Machine.incorporateFunction(F); 00969 00970 // Loop over the arguments, printing them... 00971 const FunctionType *FT = F->getFunctionType(); 00972 00973 for(Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 00974 printArgument(I); 00975 00976 // Finish printing arguments... 00977 if (FT->isVarArg()) { 00978 if (FT->getNumParams()) Out << ", "; 00979 Out << "..."; // Output varargs portion of signature! 00980 } 00981 Out << ')'; 00982 00983 if (F->hasSection()) 00984 Out << " section \"" << F->getSection() << '"'; 00985 if (F->getAlignment()) 00986 Out << " align " << F->getAlignment(); 00987 00988 if (F->isExternal()) { 00989 Out << "\n"; 00990 } else { 00991 Out << " {"; 00992 00993 // Output all of its basic blocks... for the function 00994 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I) 00995 printBasicBlock(I); 00996 00997 Out << "}\n"; 00998 } 00999 01000 Machine.purgeFunction(); 01001 } 01002 01003 /// printArgument - This member is called for every argument that is passed into 01004 /// the function. Simply print it out 01005 /// 01006 void AssemblyWriter::printArgument(const Argument *Arg) { 01007 // Insert commas as we go... the first arg doesn't get a comma 01008 if (Arg != Arg->getParent()->arg_begin()) Out << ", "; 01009 01010 // Output type... 01011 printType(Arg->getType()); 01012 01013 // Output name, if available... 01014 if (Arg->hasName()) 01015 Out << ' ' << getLLVMName(Arg->getName()); 01016 } 01017 01018 /// printBasicBlock - This member is called for each basic block in a method. 01019 /// 01020 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { 01021 if (BB->hasName()) { // Print out the label if it exists... 01022 Out << "\n" << getLLVMName(BB->getName(), false) << ':'; 01023 } else if (!BB->use_empty()) { // Don't print block # of no uses... 01024 Out << "\n; <label>:"; 01025 int Slot = Machine.getSlot(BB); 01026 if (Slot != -1) 01027 Out << Slot; 01028 else 01029 Out << "<badref>"; 01030 } 01031 01032 if (BB->getParent() == 0) 01033 Out << "\t\t; Error: Block without parent!"; 01034 else { 01035 if (BB != &BB->getParent()->front()) { // Not the entry block? 01036 // Output predecessors for the block... 01037 Out << "\t\t;"; 01038 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB); 01039 01040 if (PI == PE) { 01041 Out << " No predecessors!"; 01042 } else { 01043 Out << " preds ="; 01044 writeOperand(*PI, false, true); 01045 for (++PI; PI != PE; ++PI) { 01046 Out << ','; 01047 writeOperand(*PI, false, true); 01048 } 01049 } 01050 } 01051 } 01052 01053 Out << "\n"; 01054 01055 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out); 01056 01057 // Output all of the instructions in the basic block... 01058 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) 01059 printInstruction(*I); 01060 01061 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out); 01062 } 01063 01064 01065 /// printInfoComment - Print a little comment after the instruction indicating 01066 /// which slot it occupies. 01067 /// 01068 void AssemblyWriter::printInfoComment(const Value &V) { 01069 if (V.getType() != Type::VoidTy) { 01070 Out << "\t\t; <"; 01071 printType(V.getType()) << '>'; 01072 01073 if (!V.hasName()) { 01074 int SlotNum = Machine.getSlot(&V); 01075 if (SlotNum == -1) 01076 Out << ":<badref>"; 01077 else 01078 Out << ':' << SlotNum; // Print out the def slot taken. 01079 } 01080 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses 01081 } 01082 } 01083 01084 /// printInstruction - This member is called for each Instruction in a function.. 01085 /// 01086 void AssemblyWriter::printInstruction(const Instruction &I) { 01087 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out); 01088 01089 Out << "\t"; 01090 01091 // Print out name if it exists... 01092 if (I.hasName()) 01093 Out << getLLVMName(I.getName()) << " = "; 01094 01095 // If this is a volatile load or store, print out the volatile marker. 01096 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) || 01097 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) { 01098 Out << "volatile "; 01099 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) { 01100 // If this is a call, check if it's a tail call. 01101 Out << "tail "; 01102 } 01103 01104 // Print out the opcode... 01105 Out << I.getOpcodeName(); 01106 01107 // Print out the type of the operands... 01108 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0; 01109 01110 // Special case conditional branches to swizzle the condition out to the front 01111 if (isa<BranchInst>(I) && I.getNumOperands() > 1) { 01112 writeOperand(I.getOperand(2), true); 01113 Out << ','; 01114 writeOperand(Operand, true); 01115 Out << ','; 01116 writeOperand(I.getOperand(1), true); 01117 01118 } else if (isa<SwitchInst>(I)) { 01119 // Special case switch statement to get formatting nice and correct... 01120 writeOperand(Operand , true); Out << ','; 01121 writeOperand(I.getOperand(1), true); Out << " ["; 01122 01123 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) { 01124 Out << "\n\t\t"; 01125 writeOperand(I.getOperand(op ), true); Out << ','; 01126 writeOperand(I.getOperand(op+1), true); 01127 } 01128 Out << "\n\t]"; 01129 } else if (isa<PHINode>(I)) { 01130 Out << ' '; 01131 printType(I.getType()); 01132 Out << ' '; 01133 01134 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) { 01135 if (op) Out << ", "; 01136 Out << '['; 01137 writeOperand(I.getOperand(op ), false); Out << ','; 01138 writeOperand(I.getOperand(op+1), false); Out << " ]"; 01139 } 01140 } else if (isa<ReturnInst>(I) && !Operand) { 01141 Out << " void"; 01142 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 01143 // Print the calling convention being used. 01144 switch (CI->getCallingConv()) { 01145 case CallingConv::C: break; // default 01146 case CallingConv::CSRet: Out << " csretcc"; break; 01147 case CallingConv::Fast: Out << " fastcc"; break; 01148 case CallingConv::Cold: Out << " coldcc"; break; 01149 default: Out << " cc" << CI->getCallingConv(); break; 01150 } 01151 01152 const PointerType *PTy = cast<PointerType>(Operand->getType()); 01153 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 01154 const Type *RetTy = FTy->getReturnType(); 01155 01156 // If possible, print out the short form of the call instruction. We can 01157 // only do this if the first argument is a pointer to a nonvararg function, 01158 // and if the return type is not a pointer to a function. 01159 // 01160 if (!FTy->isVarArg() && 01161 (!isa<PointerType>(RetTy) || 01162 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) { 01163 Out << ' '; printType(RetTy); 01164 writeOperand(Operand, false); 01165 } else { 01166 writeOperand(Operand, true); 01167 } 01168 Out << '('; 01169 if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true); 01170 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) { 01171 Out << ','; 01172 writeOperand(I.getOperand(op), true); 01173 } 01174 01175 Out << " )"; 01176 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 01177 const PointerType *PTy = cast<PointerType>(Operand->getType()); 01178 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 01179 const Type *RetTy = FTy->getReturnType(); 01180 01181 // Print the calling convention being used. 01182 switch (II->getCallingConv()) { 01183 case CallingConv::C: break; // default 01184 case CallingConv::CSRet: Out << " csretcc"; break; 01185 case CallingConv::Fast: Out << " fastcc"; break; 01186 case CallingConv::Cold: Out << " coldcc"; break; 01187 default: Out << " cc" << II->getCallingConv(); break; 01188 } 01189 01190 // If possible, print out the short form of the invoke instruction. We can 01191 // only do this if the first argument is a pointer to a nonvararg function, 01192 // and if the return type is not a pointer to a function. 01193 // 01194 if (!FTy->isVarArg() && 01195 (!isa<PointerType>(RetTy) || 01196 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) { 01197 Out << ' '; printType(RetTy); 01198 writeOperand(Operand, false); 01199 } else { 01200 writeOperand(Operand, true); 01201 } 01202 01203 Out << '('; 01204 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true); 01205 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) { 01206 Out << ','; 01207 writeOperand(I.getOperand(op), true); 01208 } 01209 01210 Out << " )\n\t\t\tto"; 01211 writeOperand(II->getNormalDest(), true); 01212 Out << " unwind"; 01213 writeOperand(II->getUnwindDest(), true); 01214 01215 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) { 01216 Out << ' '; 01217 printType(AI->getType()->getElementType()); 01218 if (AI->isArrayAllocation()) { 01219 Out << ','; 01220 writeOperand(AI->getArraySize(), true); 01221 } 01222 if (AI->getAlignment()) { 01223 Out << ", align " << AI->getAlignment(); 01224 } 01225 } else if (isa<CastInst>(I)) { 01226 if (Operand) writeOperand(Operand, true); // Work with broken code 01227 Out << " to "; 01228 printType(I.getType()); 01229 } else if (isa<VAArgInst>(I)) { 01230 if (Operand) writeOperand(Operand, true); // Work with broken code 01231 Out << ", "; 01232 printType(I.getType()); 01233 } else if (Operand) { // Print the normal way... 01234 01235 // PrintAllTypes - Instructions who have operands of all the same type 01236 // omit the type from all but the first operand. If the instruction has 01237 // different type operands (for example br), then they are all printed. 01238 bool PrintAllTypes = false; 01239 const Type *TheType = Operand->getType(); 01240 01241 // Shift Left & Right print both types even for Ubyte LHS, and select prints 01242 // types even if all operands are bools. 01243 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) || 01244 isa<ShuffleVectorInst>(I)) { 01245 PrintAllTypes = true; 01246 } else { 01247 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) { 01248 Operand = I.getOperand(i); 01249 if (Operand->getType() != TheType) { 01250 PrintAllTypes = true; // We have differing types! Print them all! 01251 break; 01252 } 01253 } 01254 } 01255 01256 if (!PrintAllTypes) { 01257 Out << ' '; 01258 printType(TheType); 01259 } 01260 01261 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) { 01262 if (i) Out << ','; 01263 writeOperand(I.getOperand(i), PrintAllTypes); 01264 } 01265 } 01266 01267 printInfoComment(I); 01268 Out << "\n"; 01269 } 01270 01271 01272 //===----------------------------------------------------------------------===// 01273 // External Interface declarations 01274 //===----------------------------------------------------------------------===// 01275 01276 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 01277 SlotMachine SlotTable(this); 01278 AssemblyWriter W(o, SlotTable, this, AAW); 01279 W.write(this); 01280 } 01281 01282 void GlobalVariable::print(std::ostream &o) const { 01283 SlotMachine SlotTable(getParent()); 01284 AssemblyWriter W(o, SlotTable, getParent(), 0); 01285 W.write(this); 01286 } 01287 01288 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 01289 SlotMachine SlotTable(getParent()); 01290 AssemblyWriter W(o, SlotTable, getParent(), AAW); 01291 01292 W.write(this); 01293 } 01294 01295 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 01296 WriteAsOperand(o, this, true, true, 0); 01297 } 01298 01299 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 01300 SlotMachine SlotTable(getParent()); 01301 AssemblyWriter W(o, SlotTable, 01302 getParent() ? getParent()->getParent() : 0, AAW); 01303 W.write(this); 01304 } 01305 01306 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 01307 const Function *F = getParent() ? getParent()->getParent() : 0; 01308 SlotMachine SlotTable(F); 01309 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW); 01310 01311 W.write(this); 01312 } 01313 01314 void Constant::print(std::ostream &o) const { 01315 if (this == 0) { o << "<null> constant value\n"; return; } 01316 01317 o << ' ' << getType()->getDescription() << ' '; 01318 01319 std::map<const Type *, std::string> TypeTable; 01320 WriteConstantInt(o, this, false, TypeTable, 0); 01321 } 01322 01323 void Type::print(std::ostream &o) const { 01324 if (this == 0) 01325 o << "<null Type>"; 01326 else 01327 o << getDescription(); 01328 } 01329 01330 void Argument::print(std::ostream &o) const { 01331 WriteAsOperand(o, this, true, true, 01332 getParent() ? getParent()->getParent() : 0); 01333 } 01334 01335 // Value::dump - allow easy printing of Values from the debugger. 01336 // Located here because so much of the needed functionality is here. 01337 void Value::dump() const { print(std::cerr); } 01338 01339 // Type::dump - allow easy printing of Values from the debugger. 01340 // Located here because so much of the needed functionality is here. 01341 void Type::dump() const { print(std::cerr); } 01342 01343 //===----------------------------------------------------------------------===// 01344 // CachedWriter Class Implementation 01345 //===----------------------------------------------------------------------===// 01346 01347 void CachedWriter::setModule(const Module *M) { 01348 delete SC; delete AW; 01349 if (M) { 01350 SC = new SlotMachine(M ); 01351 AW = new AssemblyWriter(Out, *SC, M, 0); 01352 } else { 01353 SC = 0; AW = 0; 01354 } 01355 } 01356 01357 CachedWriter::~CachedWriter() { 01358 delete AW; 01359 delete SC; 01360 } 01361 01362 CachedWriter &CachedWriter::operator<<(const Value &V) { 01363 assert(AW && SC && "CachedWriter does not have a current module!"); 01364 if (const Instruction *I = dyn_cast<Instruction>(&V)) 01365 AW->write(I); 01366 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(&V)) 01367 AW->write(BB); 01368 else if (const Function *F = dyn_cast<Function>(&V)) 01369 AW->write(F); 01370 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(&V)) 01371 AW->write(GV); 01372 else 01373 AW->writeOperand(&V, true, true); 01374 return *this; 01375 } 01376 01377 CachedWriter& CachedWriter::operator<<(const Type &Ty) { 01378 if (SymbolicTypes) { 01379 const Module *M = AW->getModule(); 01380 if (M) WriteTypeSymbolic(Out, &Ty, M); 01381 } else { 01382 AW->write(&Ty); 01383 } 01384 return *this; 01385 } 01386 01387 //===----------------------------------------------------------------------===// 01388 //===-- SlotMachine Implementation 01389 //===----------------------------------------------------------------------===// 01390 01391 #if 0 01392 #define SC_DEBUG(X) std::cerr << X 01393 #else 01394 #define SC_DEBUG(X) 01395 #endif 01396 01397 // Module level constructor. Causes the contents of the Module (sans functions) 01398 // to be added to the slot table. 01399 SlotMachine::SlotMachine(const Module *M) 01400 : TheModule(M) ///< Saved for lazy initialization. 01401 , TheFunction(0) 01402 , FunctionProcessed(false) 01403 , mMap() 01404 , mTypes() 01405 , fMap() 01406 , fTypes() 01407 { 01408 } 01409 01410 // Function level constructor. Causes the contents of the Module and the one 01411 // function provided to be added to the slot table. 01412 SlotMachine::SlotMachine(const Function *F ) 01413 : TheModule( F ? F->getParent() : 0 ) ///< Saved for lazy initialization 01414 , TheFunction(F) ///< Saved for lazy initialization 01415 , FunctionProcessed(false) 01416 , mMap() 01417 , mTypes() 01418 , fMap() 01419 , fTypes() 01420 { 01421 } 01422 01423 inline void SlotMachine::initialize(void) { 01424 if ( TheModule) { 01425 processModule(); 01426 TheModule = 0; ///< Prevent re-processing next time we're called. 01427 } 01428 if ( TheFunction && ! FunctionProcessed) { 01429 processFunction(); 01430 } 01431 } 01432 01433 // Iterate through all the global variables, functions, and global 01434 // variable initializers and create slots for them. 01435 void SlotMachine::processModule() { 01436 SC_DEBUG("begin processModule!\n"); 01437 01438 // Add all of the global variables to the value table... 01439 for (Module::const_global_iterator I = TheModule->global_begin(), E = TheModule->global_end(); 01440 I != E; ++I) 01441 createSlot(I); 01442 01443 // Add all the functions to the table 01444 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 01445 I != E; ++I) 01446 createSlot(I); 01447 01448 SC_DEBUG("end processModule!\n"); 01449 } 01450 01451 01452 // Process the arguments, basic blocks, and instructions of a function. 01453 void SlotMachine::processFunction() { 01454 SC_DEBUG("begin processFunction!\n"); 01455 01456 // Add all the function arguments 01457 for(Function::const_arg_iterator AI = TheFunction->arg_begin(), 01458 AE = TheFunction->arg_end(); AI != AE; ++AI) 01459 createSlot(AI); 01460 01461 SC_DEBUG("Inserting Instructions:\n"); 01462 01463 // Add all of the basic blocks and instructions 01464 for (Function::const_iterator BB = TheFunction->begin(), 01465 E = TheFunction->end(); BB != E; ++BB) { 01466 createSlot(BB); 01467 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) { 01468 createSlot(I); 01469 } 01470 } 01471 01472 FunctionProcessed = true; 01473 01474 SC_DEBUG("end processFunction!\n"); 01475 } 01476 01477 // Clean up after incorporating a function. This is the only way 01478 // to get out of the function incorporation state that affects the 01479 // getSlot/createSlot lock. Function incorporation state is indicated 01480 // by TheFunction != 0. 01481 void SlotMachine::purgeFunction() { 01482 SC_DEBUG("begin purgeFunction!\n"); 01483 fMap.clear(); // Simply discard the function level map 01484 fTypes.clear(); 01485 TheFunction = 0; 01486 FunctionProcessed = false; 01487 SC_DEBUG("end purgeFunction!\n"); 01488 } 01489 01490 /// Get the slot number for a value. This function will assert if you 01491 /// ask for a Value that hasn't previously been inserted with createSlot. 01492 /// Types are forbidden because Type does not inherit from Value (any more). 01493 int SlotMachine::getSlot(const Value *V) { 01494 assert( V && "Can't get slot for null Value" ); 01495 assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 01496 "Can't insert a non-GlobalValue Constant into SlotMachine"); 01497 01498 // Check for uninitialized state and do lazy initialization 01499 this->initialize(); 01500 01501 // Get the type of the value 01502 const Type* VTy = V->getType(); 01503 01504 // Find the type plane in the module map 01505 TypedPlanes::const_iterator MI = mMap.find(VTy); 01506 01507 if ( TheFunction ) { 01508 // Lookup the type in the function map too 01509 TypedPlanes::const_iterator FI = fMap.find(VTy); 01510 // If there is a corresponding type plane in the function map 01511 if ( FI != fMap.end() ) { 01512 // Lookup the Value in the function map 01513 ValueMap::const_iterator FVI = FI->second.map.find(V); 01514 // If the value doesn't exist in the function map 01515 if ( FVI == FI->second.map.end() ) { 01516 // Look up the value in the module map. 01517 if (MI == mMap.end()) return -1; 01518 ValueMap::const_iterator MVI = MI->second.map.find(V); 01519 // If we didn't find it, it wasn't inserted 01520 if (MVI == MI->second.map.end()) return -1; 01521 assert( MVI != MI->second.map.end() && "Value not found"); 01522 // We found it only at the module level 01523 return MVI->second; 01524 01525 // else the value exists in the function map 01526 } else { 01527 // Return the slot number as the module's contribution to 01528 // the type plane plus the index in the function's contribution 01529 // to the type plane. 01530 if (MI != mMap.end()) 01531 return MI->second.next_slot + FVI->second; 01532 else 01533 return FVI->second; 01534 } 01535 } 01536 } 01537 01538 // N.B. Can get here only if either !TheFunction or the function doesn't 01539 // have a corresponding type plane for the Value 01540 01541 // Make sure the type plane exists 01542 if (MI == mMap.end()) return -1; 01543 // Lookup the value in the module's map 01544 ValueMap::const_iterator MVI = MI->second.map.find(V); 01545 // Make sure we found it. 01546 if (MVI == MI->second.map.end()) return -1; 01547 // Return it. 01548 return MVI->second; 01549 } 01550 01551 /// Get the slot number for a value. This function will assert if you 01552 /// ask for a Value that hasn't previously been inserted with createSlot. 01553 /// Types are forbidden because Type does not inherit from Value (any more). 01554 int SlotMachine::getSlot(const Type *Ty) { 01555 assert( Ty && "Can't get slot for null Type" ); 01556 01557 // Check for uninitialized state and do lazy initialization 01558 this->initialize(); 01559 01560 if ( TheFunction ) { 01561 // Lookup the Type in the function map 01562 TypeMap::const_iterator FTI = fTypes.map.find(Ty); 01563 // If the Type doesn't exist in the function map 01564 if ( FTI == fTypes.map.end() ) { 01565 TypeMap::const_iterator MTI = mTypes.map.find(Ty); 01566 // If we didn't find it, it wasn't inserted 01567 if (MTI == mTypes.map.end()) 01568 return -1; 01569 // We found it only at the module level 01570 return MTI->second; 01571 01572 // else the value exists in the function map 01573 } else { 01574 // Return the slot number as the module's contribution to 01575 // the type plane plus the index in the function's contribution 01576 // to the type plane. 01577 return mTypes.next_slot + FTI->second; 01578 } 01579 } 01580 01581 // N.B. Can get here only if either !TheFunction 01582 01583 // Lookup the value in the module's map 01584 TypeMap::const_iterator MTI = mTypes.map.find(Ty); 01585 // Make sure we found it. 01586 if (MTI == mTypes.map.end()) return -1; 01587 // Return it. 01588 return MTI->second; 01589 } 01590 01591 // Create a new slot, or return the existing slot if it is already 01592 // inserted. Note that the logic here parallels getSlot but instead 01593 // of asserting when the Value* isn't found, it inserts the value. 01594 unsigned SlotMachine::createSlot(const Value *V) { 01595 assert( V && "Can't insert a null Value to SlotMachine"); 01596 assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 01597 "Can't insert a non-GlobalValue Constant into SlotMachine"); 01598 01599 const Type* VTy = V->getType(); 01600 01601 // Just ignore void typed things 01602 if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value! 01603 01604 // Look up the type plane for the Value's type from the module map 01605 TypedPlanes::const_iterator MI = mMap.find(VTy); 01606 01607 if ( TheFunction ) { 01608 // Get the type plane for the Value's type from the function map 01609 TypedPlanes::const_iterator FI = fMap.find(VTy); 01610 // If there is a corresponding type plane in the function map 01611 if ( FI != fMap.end() ) { 01612 // Lookup the Value in the function map 01613 ValueMap::const_iterator FVI = FI->second.map.find(V); 01614 // If the value doesn't exist in the function map 01615 if ( FVI == FI->second.map.end() ) { 01616 // If there is no corresponding type plane in the module map 01617 if ( MI == mMap.end() ) 01618 return insertValue(V); 01619 // Look up the value in the module map 01620 ValueMap::const_iterator MVI = MI->second.map.find(V); 01621 // If we didn't find it, it wasn't inserted 01622 if ( MVI == MI->second.map.end() ) 01623 return insertValue(V); 01624 else 01625 // We found it only at the module level 01626 return MVI->second; 01627 01628 // else the value exists in the function map 01629 } else { 01630 if ( MI == mMap.end() ) 01631 return FVI->second; 01632 else 01633 // Return the slot number as the module's contribution to 01634 // the type plane plus the index in the function's contribution 01635 // to the type plane. 01636 return MI->second.next_slot + FVI->second; 01637 } 01638 01639 // else there is not a corresponding type plane in the function map 01640 } else { 01641 // If the type plane doesn't exists at the module level 01642 if ( MI == mMap.end() ) { 01643 return insertValue(V); 01644 // else type plane exists at the module level, examine it 01645 } else { 01646 // Look up the value in the module's map 01647 ValueMap::const_iterator MVI = MI->second.map.find(V); 01648 // If we didn't find it there either 01649 if ( MVI == MI->second.map.end() ) 01650 // Return the slot number as the module's contribution to 01651 // the type plane plus the index of the function map insertion. 01652 return MI->second.next_slot + insertValue(V); 01653 else 01654 return MVI->second; 01655 } 01656 } 01657 } 01658 01659 // N.B. Can only get here if !TheFunction 01660 01661 // If the module map's type plane is not for the Value's type 01662 if ( MI != mMap.end() ) { 01663 // Lookup the value in the module's map 01664 ValueMap::const_iterator MVI = MI->second.map.find(V); 01665 if ( MVI != MI->second.map.end() ) 01666 return MVI->second; 01667 } 01668 01669 return insertValue(V); 01670 } 01671 01672 // Create a new slot, or return the existing slot if it is already 01673 // inserted. Note that the logic here parallels getSlot but instead 01674 // of asserting when the Value* isn't found, it inserts the value. 01675 unsigned SlotMachine::createSlot(const Type *Ty) { 01676 assert( Ty && "Can't insert a null Type to SlotMachine"); 01677 01678 if ( TheFunction ) { 01679 // Lookup the Type in the function map 01680 TypeMap::const_iterator FTI = fTypes.map.find(Ty); 01681 // If the type doesn't exist in the function map 01682 if ( FTI == fTypes.map.end() ) { 01683 // Look up the type in the module map 01684 TypeMap::const_iterator MTI = mTypes.map.find(Ty); 01685 // If we didn't find it, it wasn't inserted 01686 if ( MTI == mTypes.map.end() ) 01687 return insertValue(Ty); 01688 else 01689 // We found it only at the module level 01690 return MTI->second; 01691 01692 // else the value exists in the function map 01693 } else { 01694 // Return the slot number as the module's contribution to 01695 // the type plane plus the index in the function's contribution 01696 // to the type plane. 01697 return mTypes.next_slot + FTI->second; 01698 } 01699 } 01700 01701 // N.B. Can only get here if !TheFunction 01702 01703 // Lookup the type in the module's map 01704 TypeMap::const_iterator MTI = mTypes.map.find(Ty); 01705 if ( MTI != mTypes.map.end() ) 01706 return MTI->second; 01707 01708 return insertValue(Ty); 01709 } 01710 01711 // Low level insert function. Minimal checking is done. This 01712 // function is just for the convenience of createSlot (above). 01713 unsigned SlotMachine::insertValue(const Value *V ) { 01714 assert(V && "Can't insert a null Value into SlotMachine!"); 01715 assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 01716 "Can't insert a non-GlobalValue Constant into SlotMachine"); 01717 01718 // If this value does not contribute to a plane (is void) 01719 // or if the value already has a name then ignore it. 01720 if (V->getType() == Type::VoidTy || V->hasName() ) { 01721 SC_DEBUG("ignored value " << *V << "\n"); 01722 return 0; // FIXME: Wrong return value 01723 } 01724 01725 const Type *VTy = V->getType(); 01726 unsigned DestSlot = 0; 01727 01728 if ( TheFunction ) { 01729 TypedPlanes::iterator I = fMap.find( VTy ); 01730 if ( I == fMap.end() ) 01731 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first; 01732 DestSlot = I->second.map[V] = I->second.next_slot++; 01733 } else { 01734 TypedPlanes::iterator I = mMap.find( VTy ); 01735 if ( I == mMap.end() ) 01736 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first; 01737 DestSlot = I->second.map[V] = I->second.next_slot++; 01738 } 01739 01740 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" << 01741 DestSlot << " ["); 01742 // G = Global, C = Constant, T = Type, F = Function, o = other 01743 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 01744 (isa<Constant>(V) ? 'C' : 'o')))); 01745 SC_DEBUG("]\n"); 01746 return DestSlot; 01747 } 01748 01749 // Low level insert function. Minimal checking is done. This 01750 // function is just for the convenience of createSlot (above). 01751 unsigned SlotMachine::insertValue(const Type *Ty ) { 01752 assert(Ty && "Can't insert a null Type into SlotMachine!"); 01753 01754 unsigned DestSlot = 0; 01755 01756 if ( TheFunction ) { 01757 DestSlot = fTypes.map[Ty] = fTypes.next_slot++; 01758 } else { 01759 DestSlot = fTypes.map[Ty] = fTypes.next_slot++; 01760 } 01761 SC_DEBUG(" Inserting type [" << DestSlot << "] = " << Ty << "\n"); 01762 return DestSlot; 01763 } 01764 01765 // vim: sw=2