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/SymbolTable.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. Its an error to ask for something not in the SlotMachine.
79 /// Its an error to ask for a Type*
80 int getSlot(const Value *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 /// CreateSlot - If the specified Value* doesn't have a name, assign it a slot
107 void CreateSlot(const Value *V);
109 /// Insert a value into the value table.
110 void insertValue(const Value *V);
112 /// Add all of the module level global variables (and their initializers)
113 /// and function declarations, but not the contents of those functions.
114 void processModule();
116 /// Add all of the functions arguments, basic blocks, and instructions
117 void processFunction();
119 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
120 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
127 /// @brief The module for which we are holding slot numbers
128 const Module* TheModule;
130 /// @brief The function for which we are holding slot numbers
131 const Function* TheFunction;
132 bool FunctionProcessed;
134 /// @brief The TypePlanes map for the module level data
137 /// @brief The TypePlanes map for the function level data
144 } // end namespace llvm
146 static RegisterPass<PrintModulePass>
147 X("printm", "Print module to stderr");
148 static RegisterPass<PrintFunctionPass>
149 Y("print","Print function to stderr");
151 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
152 std::map<const Type *, std::string> &TypeTable,
153 SlotMachine *Machine);
155 static const Module *getModuleFromVal(const Value *V) {
156 if (const Argument *MA = dyn_cast<Argument>(V))
157 return MA->getParent() ? MA->getParent()->getParent() : 0;
158 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
159 return BB->getParent() ? BB->getParent()->getParent() : 0;
160 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
161 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
162 return M ? M->getParent() : 0;
163 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
164 return GV->getParent();
168 static SlotMachine *createSlotMachine(const Value *V) {
169 if (const Argument *FA = dyn_cast<Argument>(V)) {
170 return new SlotMachine(FA->getParent());
171 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
172 return new SlotMachine(I->getParent()->getParent());
173 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
174 return new SlotMachine(BB->getParent());
175 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
176 return new SlotMachine(GV->getParent());
177 } else if (const Function *Func = dyn_cast<Function>(V)) {
178 return new SlotMachine(Func);
183 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
184 // prefixed with % (if the string only contains simple characters) or is
185 // surrounded with ""'s (if it has special chars in it).
186 static std::string getLLVMName(const std::string &Name,
187 bool prefixName = true) {
188 assert(!Name.empty() && "Cannot get empty name!");
190 // First character cannot start with a number...
191 if (Name[0] >= '0' && Name[0] <= '9')
192 return "\"" + Name + "\"";
194 // Scan to see if we have any characters that are not on the "white list"
195 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
197 assert(C != '"' && "Illegal character in LLVM value name!");
198 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
199 C != '-' && C != '.' && C != '_')
200 return "\"" + Name + "\"";
203 // If we get here, then the identifier is legal to use as a "VarID".
211 /// fillTypeNameTable - If the module has a symbol table, take all global types
212 /// and stuff their names into the TypeNames map.
214 static void fillTypeNameTable(const Module *M,
215 std::map<const Type *, std::string> &TypeNames) {
217 const TypeSymbolTable &ST = M->getTypeSymbolTable();
218 TypeSymbolTable::const_iterator TI = ST.begin();
219 for (; TI != ST.end(); ++TI) {
220 // As a heuristic, don't insert pointer to primitive types, because
221 // they are used too often to have a single useful name.
223 const Type *Ty = cast<Type>(TI->second);
224 if (!isa<PointerType>(Ty) ||
225 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
226 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
227 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
233 static void calcTypeName(const Type *Ty,
234 std::vector<const Type *> &TypeStack,
235 std::map<const Type *, std::string> &TypeNames,
236 std::string & Result){
237 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
238 Result += Ty->getDescription(); // Base case
242 // Check to see if the type is named.
243 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
244 if (I != TypeNames.end()) {
249 if (isa<OpaqueType>(Ty)) {
254 // Check to see if the Type is already on the stack...
255 unsigned Slot = 0, CurSize = TypeStack.size();
256 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
258 // This is another base case for the recursion. In this case, we know
259 // that we have looped back to a type that we have previously visited.
260 // Generate the appropriate upreference to handle this.
261 if (Slot < CurSize) {
262 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
266 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
268 switch (Ty->getTypeID()) {
269 case Type::FunctionTyID: {
270 const FunctionType *FTy = cast<FunctionType>(Ty);
271 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
274 for (FunctionType::param_iterator I = FTy->param_begin(),
275 E = FTy->param_end(); I != E; ++I) {
276 if (I != FTy->param_begin())
278 calcTypeName(*I, TypeStack, TypeNames, Result);
279 if (FTy->getParamAttrs(Idx)) {
281 Result += FunctionType::getParamAttrsText(FTy->getParamAttrs(Idx));
285 if (FTy->isVarArg()) {
286 if (FTy->getNumParams()) Result += ", ";
290 if (FTy->getParamAttrs(0)) {
292 Result += FunctionType::getParamAttrsText(FTy->getParamAttrs(0));
296 case Type::StructTyID: {
297 const StructType *STy = cast<StructType>(Ty);
301 for (StructType::element_iterator I = STy->element_begin(),
302 E = STy->element_end(); I != E; ++I) {
303 if (I != STy->element_begin())
305 calcTypeName(*I, TypeStack, TypeNames, Result);
312 case Type::PointerTyID:
313 calcTypeName(cast<PointerType>(Ty)->getElementType(),
314 TypeStack, TypeNames, Result);
317 case Type::ArrayTyID: {
318 const ArrayType *ATy = cast<ArrayType>(Ty);
319 Result += "[" + utostr(ATy->getNumElements()) + " x ";
320 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
324 case Type::PackedTyID: {
325 const PackedType *PTy = cast<PackedType>(Ty);
326 Result += "<" + utostr(PTy->getNumElements()) + " x ";
327 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
331 case Type::OpaqueTyID:
335 Result += "<unrecognized-type>";
339 TypeStack.pop_back(); // Remove self from stack...
343 /// printTypeInt - The internal guts of printing out a type that has a
344 /// potentially named portion.
346 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
347 std::map<const Type *, std::string> &TypeNames) {
348 // Primitive types always print out their description, regardless of whether
349 // they have been named or not.
351 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
352 return Out << Ty->getDescription();
354 // Check to see if the type is named.
355 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
356 if (I != TypeNames.end()) return Out << I->second;
358 // Otherwise we have a type that has not been named but is a derived type.
359 // Carefully recurse the type hierarchy to print out any contained symbolic
362 std::vector<const Type *> TypeStack;
363 std::string TypeName;
364 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
365 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
366 return (Out << TypeName);
370 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
371 /// type, iff there is an entry in the modules symbol table for the specified
372 /// type or one of it's component types. This is slower than a simple x << Type
374 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
378 // If they want us to print out a type, but there is no context, we can't
379 // print it symbolically.
381 return Out << Ty->getDescription();
383 std::map<const Type *, std::string> TypeNames;
384 fillTypeNameTable(M, TypeNames);
385 return printTypeInt(Out, Ty, TypeNames);
388 // PrintEscapedString - Print each character of the specified string, escaping
389 // it if it is not printable or if it is an escape char.
390 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
391 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
392 unsigned char C = Str[i];
393 if (isprint(C) && C != '"' && C != '\\') {
397 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
398 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
403 static const char *getPredicateText(unsigned predicate) {
404 const char * pred = "unknown";
406 case FCmpInst::FCMP_FALSE: pred = "false"; break;
407 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
408 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
409 case FCmpInst::FCMP_OGE: pred = "oge"; break;
410 case FCmpInst::FCMP_OLT: pred = "olt"; break;
411 case FCmpInst::FCMP_OLE: pred = "ole"; break;
412 case FCmpInst::FCMP_ONE: pred = "one"; break;
413 case FCmpInst::FCMP_ORD: pred = "ord"; break;
414 case FCmpInst::FCMP_UNO: pred = "uno"; break;
415 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
416 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
417 case FCmpInst::FCMP_UGE: pred = "uge"; break;
418 case FCmpInst::FCMP_ULT: pred = "ult"; break;
419 case FCmpInst::FCMP_ULE: pred = "ule"; break;
420 case FCmpInst::FCMP_UNE: pred = "une"; break;
421 case FCmpInst::FCMP_TRUE: pred = "true"; break;
422 case ICmpInst::ICMP_EQ: pred = "eq"; break;
423 case ICmpInst::ICMP_NE: pred = "ne"; break;
424 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
425 case ICmpInst::ICMP_SGE: pred = "sge"; break;
426 case ICmpInst::ICMP_SLT: pred = "slt"; break;
427 case ICmpInst::ICMP_SLE: pred = "sle"; break;
428 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
429 case ICmpInst::ICMP_UGE: pred = "uge"; break;
430 case ICmpInst::ICMP_ULT: pred = "ult"; break;
431 case ICmpInst::ICMP_ULE: pred = "ule"; break;
436 /// @brief Internal constant writer.
437 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
438 std::map<const Type *, std::string> &TypeTable,
439 SlotMachine *Machine) {
440 const int IndentSize = 4;
441 static std::string Indent = "\n";
442 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
443 Out << (CB->getValue() ? "true" : "false");
444 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
445 Out << CI->getSExtValue();
446 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
447 // We would like to output the FP constant value in exponential notation,
448 // but we cannot do this if doing so will lose precision. Check here to
449 // make sure that we only output it in exponential format if we can parse
450 // the value back and get the same value.
452 std::string StrVal = ftostr(CFP->getValue());
454 // Check to make sure that the stringized number is not some string like
455 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
456 // the string matches the "[-+]?[0-9]" regex.
458 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
459 ((StrVal[0] == '-' || StrVal[0] == '+') &&
460 (StrVal[1] >= '0' && StrVal[1] <= '9')))
461 // Reparse stringized version!
462 if (atof(StrVal.c_str()) == CFP->getValue()) {
467 // Otherwise we could not reparse it to exactly the same value, so we must
468 // output the string in hexadecimal format!
469 assert(sizeof(double) == sizeof(uint64_t) &&
470 "assuming that double is 64 bits!");
471 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
473 } else if (isa<ConstantAggregateZero>(CV)) {
474 Out << "zeroinitializer";
475 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
476 // As a special case, print the array as a string if it is an array of
477 // ubytes or an array of sbytes with positive values.
479 const Type *ETy = CA->getType()->getElementType();
480 if (CA->isString()) {
482 PrintEscapedString(CA->getAsString(), Out);
485 } else { // Cannot output in string format...
487 if (CA->getNumOperands()) {
489 printTypeInt(Out, ETy, TypeTable);
490 WriteAsOperandInternal(Out, CA->getOperand(0),
492 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
494 printTypeInt(Out, ETy, TypeTable);
495 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
500 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
501 if (CS->getType()->isPacked())
504 unsigned N = CS->getNumOperands();
507 Indent += std::string(IndentSize, ' ');
512 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
514 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
516 for (unsigned i = 1; i < N; i++) {
518 if (N > 2) Out << Indent;
519 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
521 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
523 if (N > 2) Indent.resize(Indent.size() - IndentSize);
527 if (CS->getType()->isPacked())
529 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
530 const Type *ETy = CP->getType()->getElementType();
531 assert(CP->getNumOperands() > 0 &&
532 "Number of operands for a PackedConst must be > 0");
535 printTypeInt(Out, ETy, TypeTable);
536 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
537 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
539 printTypeInt(Out, ETy, TypeTable);
540 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
543 } else if (isa<ConstantPointerNull>(CV)) {
546 } else if (isa<UndefValue>(CV)) {
549 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
550 Out << CE->getOpcodeName();
552 Out << " " << getPredicateText(CE->getPredicate());
555 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
556 printTypeInt(Out, (*OI)->getType(), TypeTable);
557 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
558 if (OI+1 != CE->op_end())
564 printTypeInt(Out, CE->getType(), TypeTable);
570 Out << "<placeholder or erroneous Constant>";
575 /// WriteAsOperand - Write the name of the specified value out to the specified
576 /// ostream. This can be useful when you just want to print int %reg126, not
577 /// the whole instruction that generated it.
579 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
580 std::map<const Type*, std::string> &TypeTable,
581 SlotMachine *Machine) {
584 Out << getLLVMName(V->getName());
586 const Constant *CV = dyn_cast<Constant>(V);
587 if (CV && !isa<GlobalValue>(CV)) {
588 WriteConstantInt(Out, CV, TypeTable, Machine);
589 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
591 if (IA->hasSideEffects())
592 Out << "sideeffect ";
594 PrintEscapedString(IA->getAsmString(), Out);
596 PrintEscapedString(IA->getConstraintString(), Out);
601 Slot = Machine->getSlot(V);
603 Machine = createSlotMachine(V);
605 Slot = Machine->getSlot(V);
618 /// WriteAsOperand - Write the name of the specified value out to the specified
619 /// ostream. This can be useful when you just want to print int %reg126, not
620 /// the whole instruction that generated it.
622 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
623 bool PrintType, const Module *Context) {
624 std::map<const Type *, std::string> TypeNames;
625 if (Context == 0) Context = getModuleFromVal(V);
628 fillTypeNameTable(Context, TypeNames);
631 printTypeInt(Out, V->getType(), TypeNames);
633 WriteAsOperandInternal(Out, V, TypeNames, 0);
640 class AssemblyWriter {
642 SlotMachine &Machine;
643 const Module *TheModule;
644 std::map<const Type *, std::string> TypeNames;
645 AssemblyAnnotationWriter *AnnotationWriter;
647 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
648 AssemblyAnnotationWriter *AAW)
649 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
651 // If the module has a symbol table, take all global types and stuff their
652 // names into the TypeNames map.
654 fillTypeNameTable(M, TypeNames);
657 inline void write(const Module *M) { printModule(M); }
658 inline void write(const GlobalVariable *G) { printGlobal(G); }
659 inline void write(const Function *F) { printFunction(F); }
660 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
661 inline void write(const Instruction *I) { printInstruction(*I); }
662 inline void write(const Constant *CPV) { printConstant(CPV); }
663 inline void write(const Type *Ty) { printType(Ty); }
665 void writeOperand(const Value *Op, bool PrintType);
667 const Module* getModule() { return TheModule; }
670 void printModule(const Module *M);
671 void printTypeSymbolTable(const TypeSymbolTable &ST);
672 void printValueSymbolTable(const SymbolTable &ST);
673 void printConstant(const Constant *CPV);
674 void printGlobal(const GlobalVariable *GV);
675 void printFunction(const Function *F);
676 void printArgument(const Argument *FA, FunctionType::ParameterAttributes A);
677 void printBasicBlock(const BasicBlock *BB);
678 void printInstruction(const Instruction &I);
680 // printType - Go to extreme measures to attempt to print out a short,
681 // symbolic version of a type name.
683 std::ostream &printType(const Type *Ty) {
684 return printTypeInt(Out, Ty, TypeNames);
687 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
688 // without considering any symbolic types that we may have equal to it.
690 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
692 // printInfoComment - Print a little comment after the instruction indicating
693 // which slot it occupies.
694 void printInfoComment(const Value &V);
696 } // end of llvm namespace
698 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
699 /// without considering any symbolic types that we may have equal to it.
701 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
702 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
703 printType(FTy->getReturnType());
706 for (FunctionType::param_iterator I = FTy->param_begin(),
707 E = FTy->param_end(); I != E; ++I) {
708 if (I != FTy->param_begin())
711 if (FTy->getParamAttrs(Idx)) {
712 Out << " " << FunctionType::getParamAttrsText(FTy->getParamAttrs(Idx));
716 if (FTy->isVarArg()) {
717 if (FTy->getNumParams()) Out << ", ";
721 if (FTy->getParamAttrs(0))
722 Out << ' ' << FunctionType::getParamAttrsText(FTy->getParamAttrs(0));
723 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
727 for (StructType::element_iterator I = STy->element_begin(),
728 E = STy->element_end(); I != E; ++I) {
729 if (I != STy->element_begin())
736 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
737 printType(PTy->getElementType()) << '*';
738 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
739 Out << '[' << ATy->getNumElements() << " x ";
740 printType(ATy->getElementType()) << ']';
741 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
742 Out << '<' << PTy->getNumElements() << " x ";
743 printType(PTy->getElementType()) << '>';
745 else if (isa<OpaqueType>(Ty)) {
748 if (!Ty->isPrimitiveType())
749 Out << "<unknown derived type>";
756 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
758 Out << "<null operand!>";
760 if (PrintType) { Out << ' '; printType(Operand->getType()); }
761 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
766 void AssemblyWriter::printModule(const Module *M) {
767 if (!M->getModuleIdentifier().empty() &&
768 // Don't print the ID if it will start a new line (which would
769 // require a comment char before it).
770 M->getModuleIdentifier().find('\n') == std::string::npos)
771 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
773 if (!M->getDataLayout().empty())
774 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
776 switch (M->getEndianness()) {
777 case Module::LittleEndian: Out << "target endian = little\n"; break;
778 case Module::BigEndian: Out << "target endian = big\n"; break;
779 case Module::AnyEndianness: break;
781 switch (M->getPointerSize()) {
782 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
783 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
784 case Module::AnyPointerSize: break;
786 if (!M->getTargetTriple().empty())
787 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
789 if (!M->getModuleInlineAsm().empty()) {
790 // Split the string into lines, to make it easier to read the .ll file.
791 std::string Asm = M->getModuleInlineAsm();
793 size_t NewLine = Asm.find_first_of('\n', CurPos);
794 while (NewLine != std::string::npos) {
795 // We found a newline, print the portion of the asm string from the
796 // last newline up to this newline.
797 Out << "module asm \"";
798 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
802 NewLine = Asm.find_first_of('\n', CurPos);
804 Out << "module asm \"";
805 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
809 // Loop over the dependent libraries and emit them.
810 Module::lib_iterator LI = M->lib_begin();
811 Module::lib_iterator LE = M->lib_end();
813 Out << "deplibs = [ ";
815 Out << '"' << *LI << '"';
823 // Loop over the symbol table, emitting all named constants.
824 printTypeSymbolTable(M->getTypeSymbolTable());
825 printValueSymbolTable(M->getValueSymbolTable());
827 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
831 Out << "\nimplementation ; Functions:\n";
833 // Output all of the functions.
834 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
838 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
839 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
841 if (!GV->hasInitializer())
842 switch (GV->getLinkage()) {
843 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
844 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
845 default: Out << "external "; break;
848 switch (GV->getLinkage()) {
849 case GlobalValue::InternalLinkage: Out << "internal "; break;
850 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
851 case GlobalValue::WeakLinkage: Out << "weak "; break;
852 case GlobalValue::AppendingLinkage: Out << "appending "; break;
853 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
854 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
855 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
856 case GlobalValue::ExternalLinkage: break;
857 case GlobalValue::GhostLinkage:
858 cerr << "GhostLinkage not allowed in AsmWriter!\n";
862 Out << (GV->isConstant() ? "constant " : "global ");
863 printType(GV->getType()->getElementType());
865 if (GV->hasInitializer()) {
866 Constant* C = cast<Constant>(GV->getInitializer());
867 assert(C && "GlobalVar initializer isn't constant?");
868 writeOperand(GV->getInitializer(), false);
871 if (GV->hasSection())
872 Out << ", section \"" << GV->getSection() << '"';
873 if (GV->getAlignment())
874 Out << ", align " << GV->getAlignment();
876 printInfoComment(*GV);
880 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
882 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
884 Out << "\t" << getLLVMName(TI->first) << " = type ";
886 // Make sure we print out at least one level of the type structure, so
887 // that we do not get %FILE = type %FILE
889 printTypeAtLeastOneLevel(TI->second) << "\n";
893 // printSymbolTable - Run through symbol table looking for constants
894 // and types. Emit their declarations.
895 void AssemblyWriter::printValueSymbolTable(const SymbolTable &ST) {
897 // Print the constants, in type plane order.
898 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
899 PI != ST.plane_end(); ++PI) {
900 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
901 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
903 for (; VI != VE; ++VI) {
904 const Value* V = VI->second;
905 const Constant *CPV = dyn_cast<Constant>(V) ;
906 if (CPV && !isa<GlobalValue>(V)) {
914 /// printConstant - Print out a constant pool entry...
916 void AssemblyWriter::printConstant(const Constant *CPV) {
917 // Don't print out unnamed constants, they will be inlined
918 if (!CPV->hasName()) return;
921 Out << "\t" << getLLVMName(CPV->getName()) << " =";
923 // Write the value out now.
924 writeOperand(CPV, true);
926 printInfoComment(*CPV);
930 /// printFunction - Print all aspects of a function.
932 void AssemblyWriter::printFunction(const Function *F) {
933 // Print out the return type and name...
936 // Ensure that no local symbols conflict with global symbols.
937 const_cast<Function*>(F)->renameLocalSymbols();
939 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
942 switch (F->getLinkage()) {
943 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
944 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
945 default: Out << "declare ";
949 switch (F->getLinkage()) {
950 case GlobalValue::InternalLinkage: Out << "internal "; break;
951 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
952 case GlobalValue::WeakLinkage: Out << "weak "; break;
953 case GlobalValue::AppendingLinkage: Out << "appending "; break;
954 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
955 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
956 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
957 case GlobalValue::ExternalLinkage: break;
958 case GlobalValue::GhostLinkage:
959 cerr << "GhostLinkage not allowed in AsmWriter!\n";
964 // Print the calling convention.
965 switch (F->getCallingConv()) {
966 case CallingConv::C: break; // default
967 case CallingConv::CSRet: Out << "csretcc "; break;
968 case CallingConv::Fast: Out << "fastcc "; break;
969 case CallingConv::Cold: Out << "coldcc "; break;
970 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
971 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
972 default: Out << "cc" << F->getCallingConv() << " "; break;
975 const FunctionType *FT = F->getFunctionType();
976 printType(F->getReturnType()) << ' ';
977 if (!F->getName().empty())
978 Out << getLLVMName(F->getName());
982 Machine.incorporateFunction(F);
984 // Loop over the arguments, printing them...
987 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
989 // Insert commas as we go... the first arg doesn't get a comma
990 if (I != F->arg_begin()) Out << ", ";
991 printArgument(I, FT->getParamAttrs(Idx));
995 // Finish printing arguments...
996 if (FT->isVarArg()) {
997 if (FT->getNumParams()) Out << ", ";
998 Out << "..."; // Output varargs portion of signature!
1001 if (FT->getParamAttrs(0))
1002 Out << ' ' << FunctionType::getParamAttrsText(FT->getParamAttrs(0));
1003 if (F->hasSection())
1004 Out << " section \"" << F->getSection() << '"';
1005 if (F->getAlignment())
1006 Out << " align " << F->getAlignment();
1008 if (F->isExternal()) {
1013 // Output all of its basic blocks... for the function
1014 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1020 Machine.purgeFunction();
1023 /// printArgument - This member is called for every argument that is passed into
1024 /// the function. Simply print it out
1026 void AssemblyWriter::printArgument(const Argument *Arg,
1027 FunctionType::ParameterAttributes attrs) {
1029 printType(Arg->getType());
1031 if (attrs != FunctionType::NoAttributeSet)
1032 Out << ' ' << FunctionType::getParamAttrsText(attrs);
1034 // Output name, if available...
1036 Out << ' ' << getLLVMName(Arg->getName());
1039 /// printBasicBlock - This member is called for each basic block in a method.
1041 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1042 if (BB->hasName()) { // Print out the label if it exists...
1043 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1044 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1045 Out << "\n; <label>:";
1046 int Slot = Machine.getSlot(BB);
1053 if (BB->getParent() == 0)
1054 Out << "\t\t; Error: Block without parent!";
1056 if (BB != &BB->getParent()->front()) { // Not the entry block?
1057 // Output predecessors for the block...
1059 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1062 Out << " No predecessors!";
1065 writeOperand(*PI, false);
1066 for (++PI; PI != PE; ++PI) {
1068 writeOperand(*PI, false);
1076 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1078 // Output all of the instructions in the basic block...
1079 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1080 printInstruction(*I);
1082 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1086 /// printInfoComment - Print a little comment after the instruction indicating
1087 /// which slot it occupies.
1089 void AssemblyWriter::printInfoComment(const Value &V) {
1090 if (V.getType() != Type::VoidTy) {
1092 printType(V.getType()) << '>';
1095 int SlotNum = Machine.getSlot(&V);
1099 Out << ':' << SlotNum; // Print out the def slot taken.
1101 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1105 // This member is called for each Instruction in a function..
1106 void AssemblyWriter::printInstruction(const Instruction &I) {
1107 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1111 // Print out name if it exists...
1113 Out << getLLVMName(I.getName()) << " = ";
1115 // If this is a volatile load or store, print out the volatile marker.
1116 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1117 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1119 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1120 // If this is a call, check if it's a tail call.
1124 // Print out the opcode...
1125 Out << I.getOpcodeName();
1127 // Print out the compare instruction predicates
1128 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1129 Out << " " << getPredicateText(FCI->getPredicate());
1130 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1131 Out << " " << getPredicateText(ICI->getPredicate());
1134 // Print out the type of the operands...
1135 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1137 // Special case conditional branches to swizzle the condition out to the front
1138 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1139 writeOperand(I.getOperand(2), true);
1141 writeOperand(Operand, true);
1143 writeOperand(I.getOperand(1), true);
1145 } else if (isa<SwitchInst>(I)) {
1146 // Special case switch statement to get formatting nice and correct...
1147 writeOperand(Operand , true); Out << ',';
1148 writeOperand(I.getOperand(1), true); Out << " [";
1150 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1152 writeOperand(I.getOperand(op ), true); Out << ',';
1153 writeOperand(I.getOperand(op+1), true);
1156 } else if (isa<PHINode>(I)) {
1158 printType(I.getType());
1161 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1162 if (op) Out << ", ";
1164 writeOperand(I.getOperand(op ), false); Out << ',';
1165 writeOperand(I.getOperand(op+1), false); Out << " ]";
1167 } else if (isa<ReturnInst>(I) && !Operand) {
1169 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1170 // Print the calling convention being used.
1171 switch (CI->getCallingConv()) {
1172 case CallingConv::C: break; // default
1173 case CallingConv::CSRet: Out << " csretcc"; break;
1174 case CallingConv::Fast: Out << " fastcc"; break;
1175 case CallingConv::Cold: Out << " coldcc"; break;
1176 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1177 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1178 default: Out << " cc" << CI->getCallingConv(); break;
1181 const PointerType *PTy = cast<PointerType>(Operand->getType());
1182 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1183 const Type *RetTy = FTy->getReturnType();
1185 // If possible, print out the short form of the call instruction. We can
1186 // only do this if the first argument is a pointer to a nonvararg function,
1187 // and if the return type is not a pointer to a function.
1189 if (!FTy->isVarArg() &&
1190 (!isa<PointerType>(RetTy) ||
1191 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1192 Out << ' '; printType(RetTy);
1193 writeOperand(Operand, false);
1195 writeOperand(Operand, true);
1198 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1201 writeOperand(I.getOperand(op), true);
1202 if (FTy->getParamAttrs(op) != FunctionType::NoAttributeSet)
1203 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op));
1206 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet)
1207 Out << ' ' << FTy->getParamAttrsText(FTy->getParamAttrs(0));
1208 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1209 const PointerType *PTy = cast<PointerType>(Operand->getType());
1210 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1211 const Type *RetTy = FTy->getReturnType();
1213 // Print the calling convention being used.
1214 switch (II->getCallingConv()) {
1215 case CallingConv::C: break; // default
1216 case CallingConv::CSRet: Out << " csretcc"; break;
1217 case CallingConv::Fast: Out << " fastcc"; break;
1218 case CallingConv::Cold: Out << " coldcc"; break;
1219 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1220 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1221 default: Out << " cc" << II->getCallingConv(); break;
1224 // If possible, print out the short form of the invoke instruction. We can
1225 // only do this if the first argument is a pointer to a nonvararg function,
1226 // and if the return type is not a pointer to a function.
1228 if (!FTy->isVarArg() &&
1229 (!isa<PointerType>(RetTy) ||
1230 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1231 Out << ' '; printType(RetTy);
1232 writeOperand(Operand, false);
1234 writeOperand(Operand, true);
1238 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1241 writeOperand(I.getOperand(op), true);
1242 if (FTy->getParamAttrs(op-2) != FunctionType::NoAttributeSet)
1243 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op-2));
1247 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet)
1248 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(0));
1249 Out << "\n\t\t\tto";
1250 writeOperand(II->getNormalDest(), true);
1252 writeOperand(II->getUnwindDest(), true);
1254 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1256 printType(AI->getType()->getElementType());
1257 if (AI->isArrayAllocation()) {
1259 writeOperand(AI->getArraySize(), true);
1261 if (AI->getAlignment()) {
1262 Out << ", align " << AI->getAlignment();
1264 } else if (isa<CastInst>(I)) {
1265 if (Operand) writeOperand(Operand, true); // Work with broken code
1267 printType(I.getType());
1268 } else if (isa<VAArgInst>(I)) {
1269 if (Operand) writeOperand(Operand, true); // Work with broken code
1271 printType(I.getType());
1272 } else if (Operand) { // Print the normal way...
1274 // PrintAllTypes - Instructions who have operands of all the same type
1275 // omit the type from all but the first operand. If the instruction has
1276 // different type operands (for example br), then they are all printed.
1277 bool PrintAllTypes = false;
1278 const Type *TheType = Operand->getType();
1280 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1281 // types even if all operands are bools.
1282 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1283 isa<ShuffleVectorInst>(I)) {
1284 PrintAllTypes = true;
1286 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1287 Operand = I.getOperand(i);
1288 if (Operand->getType() != TheType) {
1289 PrintAllTypes = true; // We have differing types! Print them all!
1295 if (!PrintAllTypes) {
1300 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1302 writeOperand(I.getOperand(i), PrintAllTypes);
1306 printInfoComment(I);
1311 //===----------------------------------------------------------------------===//
1312 // External Interface declarations
1313 //===----------------------------------------------------------------------===//
1315 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1316 SlotMachine SlotTable(this);
1317 AssemblyWriter W(o, SlotTable, this, AAW);
1321 void GlobalVariable::print(std::ostream &o) const {
1322 SlotMachine SlotTable(getParent());
1323 AssemblyWriter W(o, SlotTable, getParent(), 0);
1327 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1328 SlotMachine SlotTable(getParent());
1329 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1334 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1335 WriteAsOperand(o, this, true, 0);
1338 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1339 SlotMachine SlotTable(getParent());
1340 AssemblyWriter W(o, SlotTable,
1341 getParent() ? getParent()->getParent() : 0, AAW);
1345 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1346 const Function *F = getParent() ? getParent()->getParent() : 0;
1347 SlotMachine SlotTable(F);
1348 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1353 void Constant::print(std::ostream &o) const {
1354 if (this == 0) { o << "<null> constant value\n"; return; }
1356 o << ' ' << getType()->getDescription() << ' ';
1358 std::map<const Type *, std::string> TypeTable;
1359 WriteConstantInt(o, this, TypeTable, 0);
1362 void Type::print(std::ostream &o) const {
1366 o << getDescription();
1369 void Argument::print(std::ostream &o) const {
1370 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1373 // Value::dump - allow easy printing of Values from the debugger.
1374 // Located here because so much of the needed functionality is here.
1375 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1377 // Type::dump - allow easy printing of Values from the debugger.
1378 // Located here because so much of the needed functionality is here.
1379 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1381 //===----------------------------------------------------------------------===//
1382 // SlotMachine Implementation
1383 //===----------------------------------------------------------------------===//
1386 #define SC_DEBUG(X) cerr << X
1391 // Module level constructor. Causes the contents of the Module (sans functions)
1392 // to be added to the slot table.
1393 SlotMachine::SlotMachine(const Module *M)
1394 : TheModule(M) ///< Saved for lazy initialization.
1396 , FunctionProcessed(false)
1400 // Function level constructor. Causes the contents of the Module and the one
1401 // function provided to be added to the slot table.
1402 SlotMachine::SlotMachine(const Function *F)
1403 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1404 , TheFunction(F) ///< Saved for lazy initialization
1405 , FunctionProcessed(false)
1409 inline void SlotMachine::initialize(void) {
1412 TheModule = 0; ///< Prevent re-processing next time we're called.
1414 if (TheFunction && !FunctionProcessed)
1418 // Iterate through all the global variables, functions, and global
1419 // variable initializers and create slots for them.
1420 void SlotMachine::processModule() {
1421 SC_DEBUG("begin processModule!\n");
1423 // Add all of the unnamed global variables to the value table.
1424 for (Module::const_global_iterator I = TheModule->global_begin(),
1425 E = TheModule->global_end(); I != E; ++I)
1429 // Add all the unnamed functions to the table.
1430 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1435 SC_DEBUG("end processModule!\n");
1439 // Process the arguments, basic blocks, and instructions of a function.
1440 void SlotMachine::processFunction() {
1441 SC_DEBUG("begin processFunction!\n");
1443 // Add all the function arguments with no names.
1444 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1445 AE = TheFunction->arg_end(); AI != AE; ++AI)
1449 SC_DEBUG("Inserting Instructions:\n");
1451 // Add all of the basic blocks and instructions with no names.
1452 for (Function::const_iterator BB = TheFunction->begin(),
1453 E = TheFunction->end(); BB != E; ++BB) {
1456 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1457 if (I->getType() != Type::VoidTy && !I->hasName())
1461 FunctionProcessed = true;
1463 SC_DEBUG("end processFunction!\n");
1466 /// Clean up after incorporating a function. This is the only way to get out of
1467 /// the function incorporation state that affects getSlot/CreateSlot. Function
1468 /// incorporation state is indicated by TheFunction != 0.
1469 void SlotMachine::purgeFunction() {
1470 SC_DEBUG("begin purgeFunction!\n");
1471 fMap.clear(); // Simply discard the function level map
1473 FunctionProcessed = false;
1474 SC_DEBUG("end purgeFunction!\n");
1477 /// Get the slot number for a value. This function will assert if you
1478 /// ask for a Value that hasn't previously been inserted with CreateSlot.
1479 int SlotMachine::getSlot(const Value *V) {
1480 assert(V && "Can't get slot for null Value");
1481 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1482 "Can't insert a non-GlobalValue Constant into SlotMachine");
1484 // Check for uninitialized state and do lazy initialization
1487 // Get the type of the value
1488 const Type* VTy = V->getType();
1490 // Find the type plane in the module map
1491 TypedPlanes::const_iterator MI = mMap.find(VTy);
1494 // Lookup the type in the function map too
1495 TypedPlanes::const_iterator FI = fMap.find(VTy);
1496 // If there is a corresponding type plane in the function map
1497 if (FI != fMap.end()) {
1498 // Lookup the Value in the function map
1499 ValueMap::const_iterator FVI = FI->second.map.find(V);
1500 // If the value doesn't exist in the function map
1501 if (FVI == FI->second.map.end()) {
1502 // Look up the value in the module map.
1503 if (MI == mMap.end()) return -1;
1504 ValueMap::const_iterator MVI = MI->second.map.find(V);
1505 // If we didn't find it, it wasn't inserted
1506 if (MVI == MI->second.map.end()) return -1;
1507 assert(MVI != MI->second.map.end() && "Value not found");
1508 // We found it only at the module level
1511 // else the value exists in the function map
1513 // Return the slot number as the module's contribution to
1514 // the type plane plus the index in the function's contribution
1515 // to the type plane.
1516 if (MI != mMap.end())
1517 return MI->second.next_slot + FVI->second;
1524 // N.B. Can get here only if either !TheFunction or the function doesn't
1525 // have a corresponding type plane for the Value
1527 // Make sure the type plane exists
1528 if (MI == mMap.end()) return -1;
1529 // Lookup the value in the module's map
1530 ValueMap::const_iterator MVI = MI->second.map.find(V);
1531 // Make sure we found it.
1532 if (MVI == MI->second.map.end()) return -1;
1538 /// CreateSlot - Create a new slot for the specified value if it has no name.
1539 void SlotMachine::CreateSlot(const Value *V) {
1540 const Type* VTy = V->getType();
1541 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1542 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1543 "Can't insert a non-GlobalValue Constant into SlotMachine");
1545 // Look up the type plane for the Value's type from the module map
1546 TypedPlanes::const_iterator MI = mMap.find(VTy);
1549 // Get the type plane for the Value's type from the function map
1550 TypedPlanes::const_iterator FI = fMap.find(VTy);
1551 // If there is a corresponding type plane in the function map
1552 if (FI != fMap.end()) {
1553 // Lookup the Value in the function map.
1554 ValueMap::const_iterator FVI = FI->second.map.find(V);
1555 // If the value exists in the function map, we're done.
1556 if (FVI != FI->second.map.end())
1559 // If there is no corresponding type plane in the module map
1560 if (MI == mMap.end())
1561 return insertValue(V);
1562 // Look up the value in the module map
1563 ValueMap::const_iterator MVI = MI->second.map.find(V);
1564 // If we found it, it was already inserted
1565 if (MVI != MI->second.map.end())
1567 return insertValue(V);
1569 // else there is not a corresponding type plane in the function map
1571 // If the type plane doesn't exists at the module level
1572 if (MI == mMap.end()) {
1573 return insertValue(V);
1574 // else type plane exists at the module level, examine it
1576 // Look up the value in the module's map
1577 ValueMap::const_iterator MVI = MI->second.map.find(V);
1578 // If we didn't find it there either
1579 if (MVI == MI->second.map.end())
1580 // Return the slot number as the module's contribution to
1581 // the type plane plus the index of the function map insertion.
1582 return insertValue(V);
1589 // N.B. Can only get here if TheFunction == 0
1591 // If the module map's type plane is not for the Value's type
1592 if (MI != mMap.end()) {
1593 // Lookup the value in the module's map
1594 ValueMap::const_iterator MVI = MI->second.map.find(V);
1595 if (MVI != MI->second.map.end())
1599 return insertValue(V);
1603 // Low level insert function. Minimal checking is done. This
1604 // function is just for the convenience of CreateSlot (above).
1605 void SlotMachine::insertValue(const Value *V) {
1606 assert(V && "Can't insert a null Value into SlotMachine!");
1607 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1608 "Can't insert a non-GlobalValue Constant into SlotMachine");
1609 assert(V->getType() != Type::VoidTy && !V->hasName());
1611 const Type *VTy = V->getType();
1612 unsigned DestSlot = 0;
1615 TypedPlanes::iterator I = fMap.find(VTy);
1616 if (I == fMap.end())
1617 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1618 DestSlot = I->second.map[V] = I->second.next_slot++;
1620 TypedPlanes::iterator I = mMap.find(VTy);
1621 if (I == mMap.end())
1622 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1623 DestSlot = I->second.map[V] = I->second.next_slot++;
1626 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1628 // G = Global, F = Function, o = other
1629 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 'o')));