1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AsmAnnotationWriter.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/ValueSymbolTable.h"
28 #include "llvm/TypeSymbolTable.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Streams.h"
39 // Make virtual table appear in this compilation unit.
40 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
42 /// This class provides computation of slot numbers for LLVM Assembly writing.
43 /// @brief LLVM Assembly Writing Slot Computation.
50 /// @brief A mapping of Values to slot numbers
51 typedef std::map<const Value*, unsigned> ValueMap;
53 /// @brief A plane with next slot number and ValueMap
55 unsigned next_slot; ///< The next slot number to use
56 ValueMap map; ///< The map of Value* -> unsigned
57 ValuePlane() { next_slot = 0; } ///< Make sure we start at 0
60 /// @brief The map of planes by Type
61 typedef std::map<const Type*, ValuePlane> TypedPlanes;
64 /// @name Constructors
67 /// @brief Construct from a module
68 SlotMachine(const Module *M);
70 /// @brief Construct from a function, starting out in incorp state.
71 SlotMachine(const Function *F);
77 /// Return the slot number of the specified value in it's type
78 /// plane. If something is not in the SlotMachine, return -1.
79 int getLocalSlot(const Value *V);
80 int getGlobalSlot(const GlobalValue *V);
86 /// If you'd like to deal with a function instead of just a module, use
87 /// this method to get its data into the SlotMachine.
88 void incorporateFunction(const Function *F) {
90 FunctionProcessed = false;
93 /// After calling incorporateFunction, use this method to remove the
94 /// most recently incorporated function from the SlotMachine. This
95 /// will reset the state of the machine back to just the module contents.
99 /// @name Implementation Details
102 /// This function does the actual initialization.
103 inline void initialize();
105 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
106 void CreateModuleSlot(const GlobalValue *V);
108 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
109 void CreateFunctionSlot(const Value *V);
111 /// Add all of the module level global variables (and their initializers)
112 /// and function declarations, but not the contents of those functions.
113 void processModule();
115 /// Add all of the functions arguments, basic blocks, and instructions
116 void processFunction();
118 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
119 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
126 /// @brief The module for which we are holding slot numbers
127 const Module* TheModule;
129 /// @brief The function for which we are holding slot numbers
130 const Function* TheFunction;
131 bool FunctionProcessed;
133 /// @brief The TypePlanes map for the module level data
136 /// @brief The TypePlanes map for the function level data
143 } // end namespace llvm
145 static RegisterPass<PrintModulePass>
146 X("printm", "Print module to stderr");
147 static RegisterPass<PrintFunctionPass>
148 Y("print","Print function to stderr");
150 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
151 std::map<const Type *, std::string> &TypeTable,
152 SlotMachine *Machine);
154 static const Module *getModuleFromVal(const Value *V) {
155 if (const Argument *MA = dyn_cast<Argument>(V))
156 return MA->getParent() ? MA->getParent()->getParent() : 0;
157 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
158 return BB->getParent() ? BB->getParent()->getParent() : 0;
159 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
160 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
161 return M ? M->getParent() : 0;
162 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
163 return GV->getParent();
167 static SlotMachine *createSlotMachine(const Value *V) {
168 if (const Argument *FA = dyn_cast<Argument>(V)) {
169 return new SlotMachine(FA->getParent());
170 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
171 return new SlotMachine(I->getParent()->getParent());
172 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
173 return new SlotMachine(BB->getParent());
174 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
175 return new SlotMachine(GV->getParent());
176 } else if (const Function *Func = dyn_cast<Function>(V)) {
177 return new SlotMachine(Func);
182 /// NameNeedsQuotes - Return true if the specified llvm name should be wrapped
184 static bool NameNeedsQuotes(const std::string &Name) {
185 if (Name[0] >= '0' && Name[0] <= '9') return true;
186 // Scan to see if we have any characters that are not on the "white list"
187 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
189 assert(C != '"' && "Illegal character in LLVM value name!");
190 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
191 C != '-' && C != '.' && C != '_')
203 /// getLLVMName - Turn the specified string into an 'LLVM name', which is either
204 /// prefixed with % (if the string only contains simple characters) or is
205 /// surrounded with ""'s (if it has special chars in it).
206 static std::string getLLVMName(const std::string &Name, PrefixType Prefix) {
207 assert(!Name.empty() && "Cannot get empty name!");
209 // First character cannot start with a number...
210 if (NameNeedsQuotes(Name)) {
211 if (Prefix == GlobalPrefix)
212 return "@\"" + Name + "\"";
213 return "\"" + Name + "\"";
216 // If we get here, then the identifier is legal to use as a "VarID".
218 default: assert(0 && "Bad prefix!");
219 case GlobalPrefix: return '@' + Name;
220 case LabelPrefix: return Name;
221 case LocalPrefix: return '%' + Name;
226 /// fillTypeNameTable - If the module has a symbol table, take all global types
227 /// and stuff their names into the TypeNames map.
229 static void fillTypeNameTable(const Module *M,
230 std::map<const Type *, std::string> &TypeNames) {
232 const TypeSymbolTable &ST = M->getTypeSymbolTable();
233 TypeSymbolTable::const_iterator TI = ST.begin();
234 for (; TI != ST.end(); ++TI) {
235 // As a heuristic, don't insert pointer to primitive types, because
236 // they are used too often to have a single useful name.
238 const Type *Ty = cast<Type>(TI->second);
239 if (!isa<PointerType>(Ty) ||
240 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
241 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
242 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
243 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first, LocalPrefix)));
249 static void calcTypeName(const Type *Ty,
250 std::vector<const Type *> &TypeStack,
251 std::map<const Type *, std::string> &TypeNames,
252 std::string & Result){
253 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
254 Result += Ty->getDescription(); // Base case
258 // Check to see if the type is named.
259 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
260 if (I != TypeNames.end()) {
265 if (isa<OpaqueType>(Ty)) {
270 // Check to see if the Type is already on the stack...
271 unsigned Slot = 0, CurSize = TypeStack.size();
272 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
274 // This is another base case for the recursion. In this case, we know
275 // that we have looped back to a type that we have previously visited.
276 // Generate the appropriate upreference to handle this.
277 if (Slot < CurSize) {
278 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
282 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
284 switch (Ty->getTypeID()) {
285 case Type::IntegerTyID: {
286 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
287 Result += "i" + utostr(BitWidth);
290 case Type::FunctionTyID: {
291 const FunctionType *FTy = cast<FunctionType>(Ty);
292 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
295 for (FunctionType::param_iterator I = FTy->param_begin(),
296 E = FTy->param_end(); I != E; ++I) {
297 if (I != FTy->param_begin())
299 calcTypeName(*I, TypeStack, TypeNames, Result);
300 if (FTy->getParamAttrs(Idx)) {
302 Result += FunctionType::getParamAttrsText(FTy->getParamAttrs(Idx));
306 if (FTy->isVarArg()) {
307 if (FTy->getNumParams()) Result += ", ";
311 if (FTy->getParamAttrs(0)) {
313 Result += FunctionType::getParamAttrsText(FTy->getParamAttrs(0));
317 case Type::StructTyID: {
318 const StructType *STy = cast<StructType>(Ty);
322 for (StructType::element_iterator I = STy->element_begin(),
323 E = STy->element_end(); I != E; ++I) {
324 if (I != STy->element_begin())
326 calcTypeName(*I, TypeStack, TypeNames, Result);
333 case Type::PointerTyID:
334 calcTypeName(cast<PointerType>(Ty)->getElementType(),
335 TypeStack, TypeNames, Result);
338 case Type::ArrayTyID: {
339 const ArrayType *ATy = cast<ArrayType>(Ty);
340 Result += "[" + utostr(ATy->getNumElements()) + " x ";
341 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
345 case Type::PackedTyID: {
346 const PackedType *PTy = cast<PackedType>(Ty);
347 Result += "<" + utostr(PTy->getNumElements()) + " x ";
348 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
352 case Type::OpaqueTyID:
356 Result += "<unrecognized-type>";
360 TypeStack.pop_back(); // Remove self from stack...
364 /// printTypeInt - The internal guts of printing out a type that has a
365 /// potentially named portion.
367 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
368 std::map<const Type *, std::string> &TypeNames) {
369 // Primitive types always print out their description, regardless of whether
370 // they have been named or not.
372 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)))
373 return Out << Ty->getDescription();
375 // Check to see if the type is named.
376 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
377 if (I != TypeNames.end()) return Out << I->second;
379 // Otherwise we have a type that has not been named but is a derived type.
380 // Carefully recurse the type hierarchy to print out any contained symbolic
383 std::vector<const Type *> TypeStack;
384 std::string TypeName;
385 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
386 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
387 return (Out << TypeName);
391 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
392 /// type, iff there is an entry in the modules symbol table for the specified
393 /// type or one of it's component types. This is slower than a simple x << Type
395 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
399 // If they want us to print out a type, but there is no context, we can't
400 // print it symbolically.
402 return Out << Ty->getDescription();
404 std::map<const Type *, std::string> TypeNames;
405 fillTypeNameTable(M, TypeNames);
406 return printTypeInt(Out, Ty, TypeNames);
409 // PrintEscapedString - Print each character of the specified string, escaping
410 // it if it is not printable or if it is an escape char.
411 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
412 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
413 unsigned char C = Str[i];
414 if (isprint(C) && C != '"' && C != '\\') {
418 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
419 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
424 static const char *getPredicateText(unsigned predicate) {
425 const char * pred = "unknown";
427 case FCmpInst::FCMP_FALSE: pred = "false"; break;
428 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
429 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
430 case FCmpInst::FCMP_OGE: pred = "oge"; break;
431 case FCmpInst::FCMP_OLT: pred = "olt"; break;
432 case FCmpInst::FCMP_OLE: pred = "ole"; break;
433 case FCmpInst::FCMP_ONE: pred = "one"; break;
434 case FCmpInst::FCMP_ORD: pred = "ord"; break;
435 case FCmpInst::FCMP_UNO: pred = "uno"; break;
436 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
437 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
438 case FCmpInst::FCMP_UGE: pred = "uge"; break;
439 case FCmpInst::FCMP_ULT: pred = "ult"; break;
440 case FCmpInst::FCMP_ULE: pred = "ule"; break;
441 case FCmpInst::FCMP_UNE: pred = "une"; break;
442 case FCmpInst::FCMP_TRUE: pred = "true"; break;
443 case ICmpInst::ICMP_EQ: pred = "eq"; break;
444 case ICmpInst::ICMP_NE: pred = "ne"; break;
445 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
446 case ICmpInst::ICMP_SGE: pred = "sge"; break;
447 case ICmpInst::ICMP_SLT: pred = "slt"; break;
448 case ICmpInst::ICMP_SLE: pred = "sle"; break;
449 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
450 case ICmpInst::ICMP_UGE: pred = "uge"; break;
451 case ICmpInst::ICMP_ULT: pred = "ult"; break;
452 case ICmpInst::ICMP_ULE: pred = "ule"; break;
457 /// @brief Internal constant writer.
458 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
459 std::map<const Type *, std::string> &TypeTable,
460 SlotMachine *Machine) {
461 const int IndentSize = 4;
462 static std::string Indent = "\n";
463 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
464 if (CI->getType() == Type::Int1Ty)
465 Out << (CI->getZExtValue() ? "true" : "false");
467 Out << CI->getSExtValue();
468 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
469 // We would like to output the FP constant value in exponential notation,
470 // but we cannot do this if doing so will lose precision. Check here to
471 // make sure that we only output it in exponential format if we can parse
472 // the value back and get the same value.
474 std::string StrVal = ftostr(CFP->getValue());
476 // Check to make sure that the stringized number is not some string like
477 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
478 // the string matches the "[-+]?[0-9]" regex.
480 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
481 ((StrVal[0] == '-' || StrVal[0] == '+') &&
482 (StrVal[1] >= '0' && StrVal[1] <= '9')))
483 // Reparse stringized version!
484 if (atof(StrVal.c_str()) == CFP->getValue()) {
489 // Otherwise we could not reparse it to exactly the same value, so we must
490 // output the string in hexadecimal format!
491 assert(sizeof(double) == sizeof(uint64_t) &&
492 "assuming that double is 64 bits!");
493 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
495 } else if (isa<ConstantAggregateZero>(CV)) {
496 Out << "zeroinitializer";
497 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
498 // As a special case, print the array as a string if it is an array of
499 // ubytes or an array of sbytes with positive values.
501 const Type *ETy = CA->getType()->getElementType();
502 if (CA->isString()) {
504 PrintEscapedString(CA->getAsString(), Out);
507 } else { // Cannot output in string format...
509 if (CA->getNumOperands()) {
511 printTypeInt(Out, ETy, TypeTable);
512 WriteAsOperandInternal(Out, CA->getOperand(0),
514 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
516 printTypeInt(Out, ETy, TypeTable);
517 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
522 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
523 if (CS->getType()->isPacked())
526 unsigned N = CS->getNumOperands();
529 Indent += std::string(IndentSize, ' ');
534 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
536 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
538 for (unsigned i = 1; i < N; i++) {
540 if (N > 2) Out << Indent;
541 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
543 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
545 if (N > 2) Indent.resize(Indent.size() - IndentSize);
549 if (CS->getType()->isPacked())
551 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
552 const Type *ETy = CP->getType()->getElementType();
553 assert(CP->getNumOperands() > 0 &&
554 "Number of operands for a PackedConst must be > 0");
557 printTypeInt(Out, ETy, TypeTable);
558 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
559 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
561 printTypeInt(Out, ETy, TypeTable);
562 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
565 } else if (isa<ConstantPointerNull>(CV)) {
568 } else if (isa<UndefValue>(CV)) {
571 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
572 Out << CE->getOpcodeName();
574 Out << " " << getPredicateText(CE->getPredicate());
577 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
578 printTypeInt(Out, (*OI)->getType(), TypeTable);
579 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
580 if (OI+1 != CE->op_end())
586 printTypeInt(Out, CE->getType(), TypeTable);
592 Out << "<placeholder or erroneous Constant>";
597 /// WriteAsOperand - Write the name of the specified value out to the specified
598 /// ostream. This can be useful when you just want to print int %reg126, not
599 /// the whole instruction that generated it.
601 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
602 std::map<const Type*, std::string> &TypeTable,
603 SlotMachine *Machine) {
606 Out << getLLVMName(V->getName(),
607 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
609 const Constant *CV = dyn_cast<Constant>(V);
610 if (CV && !isa<GlobalValue>(CV)) {
611 WriteConstantInt(Out, CV, TypeTable, Machine);
612 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
614 if (IA->hasSideEffects())
615 Out << "sideeffect ";
617 PrintEscapedString(IA->getAsmString(), Out);
619 PrintEscapedString(IA->getConstraintString(), Out);
625 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
626 Slot = Machine->getGlobalSlot(GV);
629 Slot = Machine->getLocalSlot(V);
632 Machine = createSlotMachine(V);
634 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
635 Slot = Machine->getGlobalSlot(GV);
638 Slot = Machine->getLocalSlot(V);
646 Out << Prefix << Slot;
653 /// WriteAsOperand - Write the name of the specified value out to the specified
654 /// ostream. This can be useful when you just want to print int %reg126, not
655 /// the whole instruction that generated it.
657 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
658 bool PrintType, const Module *Context) {
659 std::map<const Type *, std::string> TypeNames;
660 if (Context == 0) Context = getModuleFromVal(V);
663 fillTypeNameTable(Context, TypeNames);
666 printTypeInt(Out, V->getType(), TypeNames);
668 WriteAsOperandInternal(Out, V, TypeNames, 0);
675 class AssemblyWriter {
677 SlotMachine &Machine;
678 const Module *TheModule;
679 std::map<const Type *, std::string> TypeNames;
680 AssemblyAnnotationWriter *AnnotationWriter;
682 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
683 AssemblyAnnotationWriter *AAW)
684 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
686 // If the module has a symbol table, take all global types and stuff their
687 // names into the TypeNames map.
689 fillTypeNameTable(M, TypeNames);
692 inline void write(const Module *M) { printModule(M); }
693 inline void write(const GlobalVariable *G) { printGlobal(G); }
694 inline void write(const Function *F) { printFunction(F); }
695 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
696 inline void write(const Instruction *I) { printInstruction(*I); }
697 inline void write(const Type *Ty) { printType(Ty); }
699 void writeOperand(const Value *Op, bool PrintType);
701 const Module* getModule() { return TheModule; }
704 void printModule(const Module *M);
705 void printTypeSymbolTable(const TypeSymbolTable &ST);
706 void printGlobal(const GlobalVariable *GV);
707 void printFunction(const Function *F);
708 void printArgument(const Argument *FA, FunctionType::ParameterAttributes A);
709 void printBasicBlock(const BasicBlock *BB);
710 void printInstruction(const Instruction &I);
712 // printType - Go to extreme measures to attempt to print out a short,
713 // symbolic version of a type name.
715 std::ostream &printType(const Type *Ty) {
716 return printTypeInt(Out, Ty, TypeNames);
719 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
720 // without considering any symbolic types that we may have equal to it.
722 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
724 // printInfoComment - Print a little comment after the instruction indicating
725 // which slot it occupies.
726 void printInfoComment(const Value &V);
728 } // end of llvm namespace
730 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
731 /// without considering any symbolic types that we may have equal to it.
733 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
734 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
735 Out << "i" << utostr(ITy->getBitWidth());
736 else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
737 printType(FTy->getReturnType());
740 for (FunctionType::param_iterator I = FTy->param_begin(),
741 E = FTy->param_end(); I != E; ++I) {
742 if (I != FTy->param_begin())
745 if (FTy->getParamAttrs(Idx)) {
746 Out << " " << FunctionType::getParamAttrsText(FTy->getParamAttrs(Idx));
750 if (FTy->isVarArg()) {
751 if (FTy->getNumParams()) Out << ", ";
755 if (FTy->getParamAttrs(0))
756 Out << ' ' << FunctionType::getParamAttrsText(FTy->getParamAttrs(0));
757 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
761 for (StructType::element_iterator I = STy->element_begin(),
762 E = STy->element_end(); I != E; ++I) {
763 if (I != STy->element_begin())
770 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
771 printType(PTy->getElementType()) << '*';
772 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
773 Out << '[' << ATy->getNumElements() << " x ";
774 printType(ATy->getElementType()) << ']';
775 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
776 Out << '<' << PTy->getNumElements() << " x ";
777 printType(PTy->getElementType()) << '>';
779 else if (isa<OpaqueType>(Ty)) {
782 if (!Ty->isPrimitiveType())
783 Out << "<unknown derived type>";
790 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
792 Out << "<null operand!>";
794 if (PrintType) { Out << ' '; printType(Operand->getType()); }
795 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
800 void AssemblyWriter::printModule(const Module *M) {
801 if (!M->getModuleIdentifier().empty() &&
802 // Don't print the ID if it will start a new line (which would
803 // require a comment char before it).
804 M->getModuleIdentifier().find('\n') == std::string::npos)
805 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
807 if (!M->getDataLayout().empty())
808 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
809 if (!M->getTargetTriple().empty())
810 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
812 if (!M->getModuleInlineAsm().empty()) {
813 // Split the string into lines, to make it easier to read the .ll file.
814 std::string Asm = M->getModuleInlineAsm();
816 size_t NewLine = Asm.find_first_of('\n', CurPos);
817 while (NewLine != std::string::npos) {
818 // We found a newline, print the portion of the asm string from the
819 // last newline up to this newline.
820 Out << "module asm \"";
821 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
825 NewLine = Asm.find_first_of('\n', CurPos);
827 Out << "module asm \"";
828 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
832 // Loop over the dependent libraries and emit them.
833 Module::lib_iterator LI = M->lib_begin();
834 Module::lib_iterator LE = M->lib_end();
836 Out << "deplibs = [ ";
838 Out << '"' << *LI << '"';
846 // Loop over the symbol table, emitting all named constants.
847 printTypeSymbolTable(M->getTypeSymbolTable());
849 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
853 Out << "\nimplementation ; Functions:\n";
855 // Output all of the functions.
856 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
860 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
861 if (GV->hasName()) Out << getLLVMName(GV->getName(), GlobalPrefix) << " = ";
863 if (!GV->hasInitializer())
864 switch (GV->getLinkage()) {
865 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
866 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
867 default: Out << "external "; break;
869 switch (GV->getLinkage()) {
870 case GlobalValue::InternalLinkage: Out << "internal "; break;
871 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
872 case GlobalValue::WeakLinkage: Out << "weak "; break;
873 case GlobalValue::AppendingLinkage: Out << "appending "; break;
874 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
875 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
876 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
877 case GlobalValue::ExternalLinkage: break;
878 case GlobalValue::GhostLinkage:
879 cerr << "GhostLinkage not allowed in AsmWriter!\n";
882 switch (GV->getVisibility()) {
883 default: assert(0 && "Invalid visibility style!");
884 case GlobalValue::DefaultVisibility: break;
885 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
889 Out << (GV->isConstant() ? "constant " : "global ");
890 printType(GV->getType()->getElementType());
892 if (GV->hasInitializer()) {
893 Constant* C = cast<Constant>(GV->getInitializer());
894 assert(C && "GlobalVar initializer isn't constant?");
895 writeOperand(GV->getInitializer(), false);
898 if (GV->hasSection())
899 Out << ", section \"" << GV->getSection() << '"';
900 if (GV->getAlignment())
901 Out << ", align " << GV->getAlignment();
903 printInfoComment(*GV);
907 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
909 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
911 Out << "\t" << getLLVMName(TI->first, LocalPrefix) << " = type ";
913 // Make sure we print out at least one level of the type structure, so
914 // that we do not get %FILE = type %FILE
916 printTypeAtLeastOneLevel(TI->second) << "\n";
920 /// printFunction - Print all aspects of a function.
922 void AssemblyWriter::printFunction(const Function *F) {
923 // Print out the return type and name...
926 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
928 if (F->isDeclaration())
929 switch (F->getLinkage()) {
930 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
931 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
932 default: Out << "declare ";
936 switch (F->getLinkage()) {
937 case GlobalValue::InternalLinkage: Out << "internal "; break;
938 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
939 case GlobalValue::WeakLinkage: Out << "weak "; break;
940 case GlobalValue::AppendingLinkage: Out << "appending "; break;
941 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
942 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
943 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
944 case GlobalValue::ExternalLinkage: break;
945 case GlobalValue::GhostLinkage:
946 cerr << "GhostLinkage not allowed in AsmWriter!\n";
949 switch (F->getVisibility()) {
950 default: assert(0 && "Invalid visibility style!");
951 case GlobalValue::DefaultVisibility: break;
952 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
956 // Print the calling convention.
957 switch (F->getCallingConv()) {
958 case CallingConv::C: break; // default
959 case CallingConv::Fast: Out << "fastcc "; break;
960 case CallingConv::Cold: Out << "coldcc "; break;
961 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
962 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
963 default: Out << "cc" << F->getCallingConv() << " "; break;
966 const FunctionType *FT = F->getFunctionType();
967 printType(F->getReturnType()) << ' ';
968 if (!F->getName().empty())
969 Out << getLLVMName(F->getName(), GlobalPrefix);
973 Machine.incorporateFunction(F);
975 // Loop over the arguments, printing them...
978 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
980 // Insert commas as we go... the first arg doesn't get a comma
981 if (I != F->arg_begin()) Out << ", ";
982 printArgument(I, FT->getParamAttrs(Idx));
986 // Finish printing arguments...
987 if (FT->isVarArg()) {
988 if (FT->getNumParams()) Out << ", ";
989 Out << "..."; // Output varargs portion of signature!
992 if (FT->getParamAttrs(0))
993 Out << ' ' << FunctionType::getParamAttrsText(FT->getParamAttrs(0));
995 Out << " section \"" << F->getSection() << '"';
996 if (F->getAlignment())
997 Out << " align " << F->getAlignment();
999 if (F->isDeclaration()) {
1004 // Output all of its basic blocks... for the function
1005 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1011 Machine.purgeFunction();
1014 /// printArgument - This member is called for every argument that is passed into
1015 /// the function. Simply print it out
1017 void AssemblyWriter::printArgument(const Argument *Arg,
1018 FunctionType::ParameterAttributes attrs) {
1020 printType(Arg->getType());
1022 if (attrs != FunctionType::NoAttributeSet)
1023 Out << ' ' << FunctionType::getParamAttrsText(attrs);
1025 // Output name, if available...
1027 Out << ' ' << getLLVMName(Arg->getName(), LocalPrefix);
1030 /// printBasicBlock - This member is called for each basic block in a method.
1032 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1033 if (BB->hasName()) { // Print out the label if it exists...
1034 Out << "\n" << getLLVMName(BB->getName(), LabelPrefix) << ':';
1035 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1036 Out << "\n; <label>:";
1037 int Slot = Machine.getLocalSlot(BB);
1044 if (BB->getParent() == 0)
1045 Out << "\t\t; Error: Block without parent!";
1047 if (BB != &BB->getParent()->front()) { // Not the entry block?
1048 // Output predecessors for the block...
1050 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1053 Out << " No predecessors!";
1056 writeOperand(*PI, false);
1057 for (++PI; PI != PE; ++PI) {
1059 writeOperand(*PI, false);
1067 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1069 // Output all of the instructions in the basic block...
1070 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1071 printInstruction(*I);
1073 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1077 /// printInfoComment - Print a little comment after the instruction indicating
1078 /// which slot it occupies.
1080 void AssemblyWriter::printInfoComment(const Value &V) {
1081 if (V.getType() != Type::VoidTy) {
1083 printType(V.getType()) << '>';
1087 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1088 SlotNum = Machine.getGlobalSlot(GV);
1090 SlotNum = Machine.getLocalSlot(&V);
1094 Out << ':' << SlotNum; // Print out the def slot taken.
1096 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1100 // This member is called for each Instruction in a function..
1101 void AssemblyWriter::printInstruction(const Instruction &I) {
1102 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1106 // Print out name if it exists...
1108 Out << getLLVMName(I.getName(), LocalPrefix) << " = ";
1110 // If this is a volatile load or store, print out the volatile marker.
1111 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1112 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1114 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1115 // If this is a call, check if it's a tail call.
1119 // Print out the opcode...
1120 Out << I.getOpcodeName();
1122 // Print out the compare instruction predicates
1123 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1124 Out << " " << getPredicateText(FCI->getPredicate());
1125 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1126 Out << " " << getPredicateText(ICI->getPredicate());
1129 // Print out the type of the operands...
1130 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1132 // Special case conditional branches to swizzle the condition out to the front
1133 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1134 writeOperand(I.getOperand(2), true);
1136 writeOperand(Operand, true);
1138 writeOperand(I.getOperand(1), true);
1140 } else if (isa<SwitchInst>(I)) {
1141 // Special case switch statement to get formatting nice and correct...
1142 writeOperand(Operand , true); Out << ',';
1143 writeOperand(I.getOperand(1), true); Out << " [";
1145 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1147 writeOperand(I.getOperand(op ), true); Out << ',';
1148 writeOperand(I.getOperand(op+1), true);
1151 } else if (isa<PHINode>(I)) {
1153 printType(I.getType());
1156 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1157 if (op) Out << ", ";
1159 writeOperand(I.getOperand(op ), false); Out << ',';
1160 writeOperand(I.getOperand(op+1), false); Out << " ]";
1162 } else if (isa<ReturnInst>(I) && !Operand) {
1164 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1165 // Print the calling convention being used.
1166 switch (CI->getCallingConv()) {
1167 case CallingConv::C: break; // default
1168 case CallingConv::Fast: Out << " fastcc"; break;
1169 case CallingConv::Cold: Out << " coldcc"; break;
1170 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1171 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1172 default: Out << " cc" << CI->getCallingConv(); break;
1175 const PointerType *PTy = cast<PointerType>(Operand->getType());
1176 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1177 const Type *RetTy = FTy->getReturnType();
1179 // If possible, print out the short form of the call instruction. We can
1180 // only do this if the first argument is a pointer to a nonvararg function,
1181 // and if the return type is not a pointer to a function.
1183 if (!FTy->isVarArg() &&
1184 (!isa<PointerType>(RetTy) ||
1185 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1186 Out << ' '; printType(RetTy);
1187 writeOperand(Operand, false);
1189 writeOperand(Operand, true);
1192 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1195 writeOperand(I.getOperand(op), true);
1196 if (FTy->getParamAttrs(op) != FunctionType::NoAttributeSet)
1197 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op));
1200 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet)
1201 Out << ' ' << FTy->getParamAttrsText(FTy->getParamAttrs(0));
1202 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1203 const PointerType *PTy = cast<PointerType>(Operand->getType());
1204 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1205 const Type *RetTy = FTy->getReturnType();
1207 // Print the calling convention being used.
1208 switch (II->getCallingConv()) {
1209 case CallingConv::C: break; // default
1210 case CallingConv::Fast: Out << " fastcc"; break;
1211 case CallingConv::Cold: Out << " coldcc"; break;
1212 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1213 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1214 default: Out << " cc" << II->getCallingConv(); break;
1217 // If possible, print out the short form of the invoke instruction. We can
1218 // only do this if the first argument is a pointer to a nonvararg function,
1219 // and if the return type is not a pointer to a function.
1221 if (!FTy->isVarArg() &&
1222 (!isa<PointerType>(RetTy) ||
1223 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1224 Out << ' '; printType(RetTy);
1225 writeOperand(Operand, false);
1227 writeOperand(Operand, true);
1231 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1234 writeOperand(I.getOperand(op), true);
1235 if (FTy->getParamAttrs(op-2) != FunctionType::NoAttributeSet)
1236 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op-2));
1240 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet)
1241 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(0));
1242 Out << "\n\t\t\tto";
1243 writeOperand(II->getNormalDest(), true);
1245 writeOperand(II->getUnwindDest(), true);
1247 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1249 printType(AI->getType()->getElementType());
1250 if (AI->isArrayAllocation()) {
1252 writeOperand(AI->getArraySize(), true);
1254 if (AI->getAlignment()) {
1255 Out << ", align " << AI->getAlignment();
1257 } else if (isa<CastInst>(I)) {
1258 if (Operand) writeOperand(Operand, true); // Work with broken code
1260 printType(I.getType());
1261 } else if (isa<VAArgInst>(I)) {
1262 if (Operand) writeOperand(Operand, true); // Work with broken code
1264 printType(I.getType());
1265 } else if (Operand) { // Print the normal way...
1267 // PrintAllTypes - Instructions who have operands of all the same type
1268 // omit the type from all but the first operand. If the instruction has
1269 // different type operands (for example br), then they are all printed.
1270 bool PrintAllTypes = false;
1271 const Type *TheType = Operand->getType();
1273 // Select, Store and ShuffleVector always print all types.
1274 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)) {
1275 PrintAllTypes = true;
1277 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1278 Operand = I.getOperand(i);
1279 if (Operand->getType() != TheType) {
1280 PrintAllTypes = true; // We have differing types! Print them all!
1286 if (!PrintAllTypes) {
1291 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1293 writeOperand(I.getOperand(i), PrintAllTypes);
1297 printInfoComment(I);
1302 //===----------------------------------------------------------------------===//
1303 // External Interface declarations
1304 //===----------------------------------------------------------------------===//
1306 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1307 SlotMachine SlotTable(this);
1308 AssemblyWriter W(o, SlotTable, this, AAW);
1312 void GlobalVariable::print(std::ostream &o) const {
1313 SlotMachine SlotTable(getParent());
1314 AssemblyWriter W(o, SlotTable, getParent(), 0);
1318 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1319 SlotMachine SlotTable(getParent());
1320 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1325 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1326 WriteAsOperand(o, this, true, 0);
1329 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1330 SlotMachine SlotTable(getParent());
1331 AssemblyWriter W(o, SlotTable,
1332 getParent() ? getParent()->getParent() : 0, AAW);
1336 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1337 const Function *F = getParent() ? getParent()->getParent() : 0;
1338 SlotMachine SlotTable(F);
1339 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1344 void Constant::print(std::ostream &o) const {
1345 if (this == 0) { o << "<null> constant value\n"; return; }
1347 o << ' ' << getType()->getDescription() << ' ';
1349 std::map<const Type *, std::string> TypeTable;
1350 WriteConstantInt(o, this, TypeTable, 0);
1353 void Type::print(std::ostream &o) const {
1357 o << getDescription();
1360 void Argument::print(std::ostream &o) const {
1361 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1364 // Value::dump - allow easy printing of Values from the debugger.
1365 // Located here because so much of the needed functionality is here.
1366 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1368 // Type::dump - allow easy printing of Values from the debugger.
1369 // Located here because so much of the needed functionality is here.
1370 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1372 //===----------------------------------------------------------------------===//
1373 // SlotMachine Implementation
1374 //===----------------------------------------------------------------------===//
1377 #define SC_DEBUG(X) cerr << X
1382 // Module level constructor. Causes the contents of the Module (sans functions)
1383 // to be added to the slot table.
1384 SlotMachine::SlotMachine(const Module *M)
1385 : TheModule(M) ///< Saved for lazy initialization.
1387 , FunctionProcessed(false)
1391 // Function level constructor. Causes the contents of the Module and the one
1392 // function provided to be added to the slot table.
1393 SlotMachine::SlotMachine(const Function *F)
1394 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1395 , TheFunction(F) ///< Saved for lazy initialization
1396 , FunctionProcessed(false)
1400 inline void SlotMachine::initialize() {
1403 TheModule = 0; ///< Prevent re-processing next time we're called.
1405 if (TheFunction && !FunctionProcessed)
1409 // Iterate through all the global variables, functions, and global
1410 // variable initializers and create slots for them.
1411 void SlotMachine::processModule() {
1412 SC_DEBUG("begin processModule!\n");
1414 // Add all of the unnamed global variables to the value table.
1415 for (Module::const_global_iterator I = TheModule->global_begin(),
1416 E = TheModule->global_end(); I != E; ++I)
1418 CreateModuleSlot(I);
1420 // Add all the unnamed functions to the table.
1421 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1424 CreateModuleSlot(I);
1426 SC_DEBUG("end processModule!\n");
1430 // Process the arguments, basic blocks, and instructions of a function.
1431 void SlotMachine::processFunction() {
1432 SC_DEBUG("begin processFunction!\n");
1434 // Add all the function arguments with no names.
1435 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1436 AE = TheFunction->arg_end(); AI != AE; ++AI)
1438 CreateFunctionSlot(AI);
1440 SC_DEBUG("Inserting Instructions:\n");
1442 // Add all of the basic blocks and instructions with no names.
1443 for (Function::const_iterator BB = TheFunction->begin(),
1444 E = TheFunction->end(); BB != E; ++BB) {
1446 CreateFunctionSlot(BB);
1447 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1448 if (I->getType() != Type::VoidTy && !I->hasName())
1449 CreateFunctionSlot(I);
1452 FunctionProcessed = true;
1454 SC_DEBUG("end processFunction!\n");
1457 /// Clean up after incorporating a function. This is the only way to get out of
1458 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1459 /// incorporation state is indicated by TheFunction != 0.
1460 void SlotMachine::purgeFunction() {
1461 SC_DEBUG("begin purgeFunction!\n");
1462 fMap.clear(); // Simply discard the function level map
1464 FunctionProcessed = false;
1465 SC_DEBUG("end purgeFunction!\n");
1468 /// getGlobalSlot - Get the slot number of a global value.
1469 int SlotMachine::getGlobalSlot(const GlobalValue *V) {
1470 // Check for uninitialized state and do lazy initialization.
1473 // Find the type plane in the module map
1474 TypedPlanes::const_iterator MI = mMap.find(V->getType());
1475 if (MI == mMap.end()) return -1;
1477 // Lookup the value in the module plane's map.
1478 ValueMap::const_iterator MVI = MI->second.map.find(V);
1479 return MVI != MI->second.map.end() ? int(MVI->second) : -1;
1483 /// getLocalSlot - Get the slot number for a value that is local to a function.
1484 int SlotMachine::getLocalSlot(const Value *V) {
1485 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1487 // Check for uninitialized state and do lazy initialization.
1490 // Get the type of the value
1491 const Type *VTy = V->getType();
1493 TypedPlanes::const_iterator FI = fMap.find(VTy);
1494 if (FI == fMap.end()) return -1;
1496 // Lookup the Value in the function and module maps.
1497 ValueMap::const_iterator FVI = FI->second.map.find(V);
1499 // If the value doesn't exist in the function map, it is a <badref>
1500 if (FVI == FI->second.map.end()) return -1;
1506 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1507 void SlotMachine::CreateModuleSlot(const GlobalValue *V) {
1508 assert(V && "Can't insert a null Value into SlotMachine!");
1510 unsigned DestSlot = 0;
1511 const Type *VTy = V->getType();
1513 ValuePlane &PlaneMap = mMap[VTy];
1514 DestSlot = PlaneMap.map[V] = PlaneMap.next_slot++;
1516 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1518 // G = Global, F = Function, o = other
1519 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : 'F') << "]\n");
1523 /// CreateSlot - Create a new slot for the specified value if it has no name.
1524 void SlotMachine::CreateFunctionSlot(const Value *V) {
1525 const Type *VTy = V->getType();
1526 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1528 unsigned DestSlot = 0;
1530 ValuePlane &PlaneMap = fMap[VTy];
1531 DestSlot = PlaneMap.map[V] = PlaneMap.next_slot++;
1533 // G = Global, F = Function, o = other
1534 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1535 DestSlot << " [o]\n");