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/CachedWriter.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/Assembly/AsmAnnotationWriter.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instruction.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Module.h"
28 #include "llvm/SymbolTable.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 /// Values can be crammed into here at will. If they haven't
106 /// been inserted already, they get inserted, otherwise they are ignored.
107 /// Either way, the slot number for the Value* is returned.
108 unsigned getOrCreateSlot(const Value *V);
110 /// Insert a value into the value table. Return the slot number
111 /// that it now occupies. BadThings(TM) will happen if you insert a
112 /// Value that's already been inserted.
113 unsigned insertValue(const Value *V);
115 /// Add all of the module level global variables (and their initializers)
116 /// and function declarations, but not the contents of those functions.
117 void processModule();
119 /// Add all of the functions arguments, basic blocks, and instructions
120 void processFunction();
122 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
123 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
130 /// @brief The module for which we are holding slot numbers
131 const Module* TheModule;
133 /// @brief The function for which we are holding slot numbers
134 const Function* TheFunction;
135 bool FunctionProcessed;
137 /// @brief The TypePlanes map for the module level data
140 /// @brief The TypePlanes map for the function level data
147 } // end namespace llvm
149 static RegisterPass<PrintModulePass>
150 X("printm", "Print module to stderr");
151 static RegisterPass<PrintFunctionPass>
152 Y("print","Print function to stderr");
154 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
156 std::map<const Type *, std::string> &TypeTable,
157 SlotMachine *Machine);
159 static const Module *getModuleFromVal(const Value *V) {
160 if (const Argument *MA = dyn_cast<Argument>(V))
161 return MA->getParent() ? MA->getParent()->getParent() : 0;
162 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
163 return BB->getParent() ? BB->getParent()->getParent() : 0;
164 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
165 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
166 return M ? M->getParent() : 0;
167 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
168 return GV->getParent();
172 static SlotMachine *createSlotMachine(const Value *V) {
173 if (const Argument *FA = dyn_cast<Argument>(V)) {
174 return new SlotMachine(FA->getParent());
175 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
176 return new SlotMachine(I->getParent()->getParent());
177 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
178 return new SlotMachine(BB->getParent());
179 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
180 return new SlotMachine(GV->getParent());
181 } else if (const Function *Func = dyn_cast<Function>(V)) {
182 return new SlotMachine(Func);
187 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
188 // prefixed with % (if the string only contains simple characters) or is
189 // surrounded with ""'s (if it has special chars in it).
190 static std::string getLLVMName(const std::string &Name,
191 bool prefixName = true) {
192 assert(!Name.empty() && "Cannot get empty name!");
194 // First character cannot start with a number...
195 if (Name[0] >= '0' && Name[0] <= '9')
196 return "\"" + Name + "\"";
198 // Scan to see if we have any characters that are not on the "white list"
199 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
201 assert(C != '"' && "Illegal character in LLVM value name!");
202 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
203 C != '-' && C != '.' && C != '_')
204 return "\"" + Name + "\"";
207 // If we get here, then the identifier is legal to use as a "VarID".
215 /// fillTypeNameTable - If the module has a symbol table, take all global types
216 /// and stuff their names into the TypeNames map.
218 static void fillTypeNameTable(const Module *M,
219 std::map<const Type *, std::string> &TypeNames) {
221 const SymbolTable &ST = M->getSymbolTable();
222 SymbolTable::type_const_iterator TI = ST.type_begin();
223 for (; TI != ST.type_end(); ++TI) {
224 // As a heuristic, don't insert pointer to primitive types, because
225 // they are used too often to have a single useful name.
227 const Type *Ty = cast<Type>(TI->second);
228 if (!isa<PointerType>(Ty) ||
229 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
230 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
231 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
237 static void calcTypeName(const Type *Ty,
238 std::vector<const Type *> &TypeStack,
239 std::map<const Type *, std::string> &TypeNames,
240 std::string & Result){
241 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
242 Result += Ty->getDescription(); // Base case
246 // Check to see if the type is named.
247 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
248 if (I != TypeNames.end()) {
253 if (isa<OpaqueType>(Ty)) {
258 // Check to see if the Type is already on the stack...
259 unsigned Slot = 0, CurSize = TypeStack.size();
260 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
262 // This is another base case for the recursion. In this case, we know
263 // that we have looped back to a type that we have previously visited.
264 // Generate the appropriate upreference to handle this.
265 if (Slot < CurSize) {
266 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
270 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
272 switch (Ty->getTypeID()) {
273 case Type::FunctionTyID: {
274 const FunctionType *FTy = cast<FunctionType>(Ty);
275 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
277 for (FunctionType::param_iterator I = FTy->param_begin(),
278 E = FTy->param_end(); I != E; ++I) {
279 if (I != FTy->param_begin())
281 calcTypeName(*I, TypeStack, TypeNames, Result);
283 if (FTy->isVarArg()) {
284 if (FTy->getNumParams()) Result += ", ";
290 case Type::StructTyID: {
291 const StructType *STy = cast<StructType>(Ty);
293 for (StructType::element_iterator I = STy->element_begin(),
294 E = STy->element_end(); I != E; ++I) {
295 if (I != STy->element_begin())
297 calcTypeName(*I, TypeStack, TypeNames, Result);
302 case Type::PointerTyID:
303 calcTypeName(cast<PointerType>(Ty)->getElementType(),
304 TypeStack, TypeNames, Result);
307 case Type::ArrayTyID: {
308 const ArrayType *ATy = cast<ArrayType>(Ty);
309 Result += "[" + utostr(ATy->getNumElements()) + " x ";
310 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
314 case Type::PackedTyID: {
315 const PackedType *PTy = cast<PackedType>(Ty);
316 Result += "<" + utostr(PTy->getNumElements()) + " x ";
317 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
321 case Type::OpaqueTyID:
325 Result += "<unrecognized-type>";
328 TypeStack.pop_back(); // Remove self from stack...
333 /// printTypeInt - The internal guts of printing out a type that has a
334 /// potentially named portion.
336 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
337 std::map<const Type *, std::string> &TypeNames) {
338 // Primitive types always print out their description, regardless of whether
339 // they have been named or not.
341 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
342 return Out << Ty->getDescription();
344 // Check to see if the type is named.
345 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
346 if (I != TypeNames.end()) return Out << I->second;
348 // Otherwise we have a type that has not been named but is a derived type.
349 // Carefully recurse the type hierarchy to print out any contained symbolic
352 std::vector<const Type *> TypeStack;
353 std::string TypeName;
354 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
355 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
356 return (Out << TypeName);
360 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
361 /// type, iff there is an entry in the modules symbol table for the specified
362 /// type or one of it's component types. This is slower than a simple x << Type
364 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
368 // If they want us to print out a type, attempt to make it symbolic if there
369 // is a symbol table in the module...
371 std::map<const Type *, std::string> TypeNames;
372 fillTypeNameTable(M, TypeNames);
374 return printTypeInt(Out, Ty, TypeNames);
376 return Out << Ty->getDescription();
380 // PrintEscapedString - Print each character of the specified string, escaping
381 // it if it is not printable or if it is an escape char.
382 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
383 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
384 unsigned char C = Str[i];
385 if (isprint(C) && C != '"' && C != '\\') {
389 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
390 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
395 static const char * getPredicateText(unsigned predicate) {
396 const char * pred = "unknown";
398 case FCmpInst::FCMP_FALSE: pred = "false"; break;
399 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
400 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
401 case FCmpInst::FCMP_OGE: pred = "oge"; break;
402 case FCmpInst::FCMP_OLT: pred = "olt"; break;
403 case FCmpInst::FCMP_OLE: pred = "ole"; break;
404 case FCmpInst::FCMP_ONE: pred = "one"; break;
405 case FCmpInst::FCMP_ORD: pred = "ord"; break;
406 case FCmpInst::FCMP_UNO: pred = "uno"; break;
407 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
408 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
409 case FCmpInst::FCMP_UGE: pred = "uge"; break;
410 case FCmpInst::FCMP_ULT: pred = "ult"; break;
411 case FCmpInst::FCMP_ULE: pred = "ule"; break;
412 case FCmpInst::FCMP_UNE: pred = "une"; break;
413 case FCmpInst::FCMP_TRUE: pred = "true"; break;
414 case ICmpInst::ICMP_EQ: pred = "eq"; break;
415 case ICmpInst::ICMP_NE: pred = "ne"; break;
416 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
417 case ICmpInst::ICMP_SGE: pred = "sge"; break;
418 case ICmpInst::ICMP_SLT: pred = "slt"; break;
419 case ICmpInst::ICMP_SLE: pred = "sle"; break;
420 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
421 case ICmpInst::ICMP_UGE: pred = "uge"; break;
422 case ICmpInst::ICMP_ULT: pred = "ult"; break;
423 case ICmpInst::ICMP_ULE: pred = "ule"; break;
428 /// @brief Internal constant writer.
429 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
431 std::map<const Type *, std::string> &TypeTable,
432 SlotMachine *Machine) {
433 const int IndentSize = 4;
434 static std::string Indent = "\n";
435 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
436 Out << (CB->getValue() ? "true" : "false");
437 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
438 if (CI->getType()->isSigned())
439 Out << CI->getSExtValue();
441 Out << CI->getZExtValue();
442 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
443 // We would like to output the FP constant value in exponential notation,
444 // but we cannot do this if doing so will lose precision. Check here to
445 // make sure that we only output it in exponential format if we can parse
446 // the value back and get the same value.
448 std::string StrVal = ftostr(CFP->getValue());
450 // Check to make sure that the stringized number is not some string like
451 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
452 // the string matches the "[-+]?[0-9]" regex.
454 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
455 ((StrVal[0] == '-' || StrVal[0] == '+') &&
456 (StrVal[1] >= '0' && StrVal[1] <= '9')))
457 // Reparse stringized version!
458 if (atof(StrVal.c_str()) == CFP->getValue()) {
463 // Otherwise we could not reparse it to exactly the same value, so we must
464 // output the string in hexadecimal format!
465 assert(sizeof(double) == sizeof(uint64_t) &&
466 "assuming that double is 64 bits!");
467 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
469 } else if (isa<ConstantAggregateZero>(CV)) {
470 Out << "zeroinitializer";
471 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
472 // As a special case, print the array as a string if it is an array of
473 // ubytes or an array of sbytes with positive values.
475 const Type *ETy = CA->getType()->getElementType();
476 if (CA->isString()) {
478 PrintEscapedString(CA->getAsString(), Out);
481 } else { // Cannot output in string format...
483 if (CA->getNumOperands()) {
485 printTypeInt(Out, ETy, TypeTable);
486 WriteAsOperandInternal(Out, CA->getOperand(0),
487 PrintName, TypeTable, Machine);
488 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
490 printTypeInt(Out, ETy, TypeTable);
491 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
497 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
499 unsigned N = CS->getNumOperands();
502 Indent += std::string(IndentSize, ' ');
507 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
509 WriteAsOperandInternal(Out, CS->getOperand(0),
510 PrintName, TypeTable, Machine);
512 for (unsigned i = 1; i < N; i++) {
514 if (N > 2) Out << Indent;
515 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
517 WriteAsOperandInternal(Out, CS->getOperand(i),
518 PrintName, TypeTable, Machine);
520 if (N > 2) Indent.resize(Indent.size() - IndentSize);
524 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
525 const Type *ETy = CP->getType()->getElementType();
526 assert(CP->getNumOperands() > 0 &&
527 "Number of operands for a PackedConst must be > 0");
530 printTypeInt(Out, ETy, TypeTable);
531 WriteAsOperandInternal(Out, CP->getOperand(0),
532 PrintName, TypeTable, Machine);
533 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
535 printTypeInt(Out, ETy, TypeTable);
536 WriteAsOperandInternal(Out, CP->getOperand(i), PrintName,
540 } else if (isa<ConstantPointerNull>(CV)) {
543 } else if (isa<UndefValue>(CV)) {
546 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
547 Out << CE->getOpcodeName();
549 Out << " " << getPredicateText(CE->getPredicate());
552 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
553 printTypeInt(Out, (*OI)->getType(), TypeTable);
554 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
555 if (OI+1 != CE->op_end())
561 printTypeInt(Out, CE->getType(), TypeTable);
567 Out << "<placeholder or erroneous Constant>";
572 /// WriteAsOperand - Write the name of the specified value out to the specified
573 /// ostream. This can be useful when you just want to print int %reg126, not
574 /// the whole instruction that generated it.
576 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
578 std::map<const Type*, std::string> &TypeTable,
579 SlotMachine *Machine) {
581 if ((PrintName || isa<GlobalValue>(V)) && V->hasName())
582 Out << getLLVMName(V->getName());
584 const Constant *CV = dyn_cast<Constant>(V);
585 if (CV && !isa<GlobalValue>(CV)) {
586 WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
587 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
589 if (IA->hasSideEffects())
590 Out << "sideeffect ";
592 PrintEscapedString(IA->getAsmString(), Out);
594 PrintEscapedString(IA->getConstraintString(), Out);
599 Slot = Machine->getSlot(V);
601 Machine = createSlotMachine(V);
603 Slot = Machine->getSlot(V);
616 /// WriteAsOperand - Write the name of the specified value out to the specified
617 /// ostream. This can be useful when you just want to print int %reg126, not
618 /// the whole instruction that generated it.
620 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
621 bool PrintType, const Module *Context) {
622 std::map<const Type *, std::string> TypeNames;
623 if (Context == 0) Context = getModuleFromVal(V);
626 fillTypeNameTable(Context, TypeNames);
629 printTypeInt(Out, V->getType(), TypeNames);
631 WriteAsOperandInternal(Out, V, true, TypeNames, 0);
638 class AssemblyWriter {
640 SlotMachine &Machine;
641 const Module *TheModule;
642 std::map<const Type *, std::string> TypeNames;
643 AssemblyAnnotationWriter *AnnotationWriter;
645 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
646 AssemblyAnnotationWriter *AAW)
647 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
649 // If the module has a symbol table, take all global types and stuff their
650 // names into the TypeNames map.
652 fillTypeNameTable(M, TypeNames);
655 inline void write(const Module *M) { printModule(M); }
656 inline void write(const GlobalVariable *G) { printGlobal(G); }
657 inline void write(const Function *F) { printFunction(F); }
658 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
659 inline void write(const Instruction *I) { printInstruction(*I); }
660 inline void write(const Constant *CPV) { printConstant(CPV); }
661 inline void write(const Type *Ty) { printType(Ty); }
663 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
665 const Module* getModule() { return TheModule; }
668 void printModule(const Module *M);
669 void printSymbolTable(const SymbolTable &ST);
670 void printConstant(const Constant *CPV);
671 void printGlobal(const GlobalVariable *GV);
672 void printFunction(const Function *F);
673 void printArgument(const Argument *FA);
674 void printBasicBlock(const BasicBlock *BB);
675 void printInstruction(const Instruction &I);
677 // printType - Go to extreme measures to attempt to print out a short,
678 // symbolic version of a type name.
680 std::ostream &printType(const Type *Ty) {
681 return printTypeInt(Out, Ty, TypeNames);
684 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
685 // without considering any symbolic types that we may have equal to it.
687 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
689 // printInfoComment - Print a little comment after the instruction indicating
690 // which slot it occupies.
691 void printInfoComment(const Value &V);
693 } // end of llvm namespace
695 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
696 /// without considering any symbolic types that we may have equal to it.
698 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
699 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
700 printType(FTy->getReturnType()) << " (";
701 for (FunctionType::param_iterator I = FTy->param_begin(),
702 E = FTy->param_end(); I != E; ++I) {
703 if (I != FTy->param_begin())
707 if (FTy->isVarArg()) {
708 if (FTy->getNumParams()) Out << ", ";
712 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
714 for (StructType::element_iterator I = STy->element_begin(),
715 E = STy->element_end(); I != E; ++I) {
716 if (I != STy->element_begin())
721 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
722 printType(PTy->getElementType()) << '*';
723 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
724 Out << '[' << ATy->getNumElements() << " x ";
725 printType(ATy->getElementType()) << ']';
726 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
727 Out << '<' << PTy->getNumElements() << " x ";
728 printType(PTy->getElementType()) << '>';
730 else if (isa<OpaqueType>(Ty)) {
733 if (!Ty->isPrimitiveType())
734 Out << "<unknown derived type>";
741 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
744 if (PrintType) { Out << ' '; printType(Operand->getType()); }
745 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Machine);
747 Out << "<null operand!>";
752 void AssemblyWriter::printModule(const Module *M) {
753 if (!M->getModuleIdentifier().empty() &&
754 // Don't print the ID if it will start a new line (which would
755 // require a comment char before it).
756 M->getModuleIdentifier().find('\n') == std::string::npos)
757 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
759 if (!M->getDataLayout().empty())
760 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
762 switch (M->getEndianness()) {
763 case Module::LittleEndian: Out << "target endian = little\n"; break;
764 case Module::BigEndian: Out << "target endian = big\n"; break;
765 case Module::AnyEndianness: break;
767 switch (M->getPointerSize()) {
768 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
769 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
770 case Module::AnyPointerSize: break;
772 if (!M->getTargetTriple().empty())
773 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
775 if (!M->getModuleInlineAsm().empty()) {
776 // Split the string into lines, to make it easier to read the .ll file.
777 std::string Asm = M->getModuleInlineAsm();
779 size_t NewLine = Asm.find_first_of('\n', CurPos);
780 while (NewLine != std::string::npos) {
781 // We found a newline, print the portion of the asm string from the
782 // last newline up to this newline.
783 Out << "module asm \"";
784 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
788 NewLine = Asm.find_first_of('\n', CurPos);
790 Out << "module asm \"";
791 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
795 // Loop over the dependent libraries and emit them.
796 Module::lib_iterator LI = M->lib_begin();
797 Module::lib_iterator LE = M->lib_end();
799 Out << "deplibs = [ ";
801 Out << '"' << *LI << '"';
809 // Loop over the symbol table, emitting all named constants.
810 printSymbolTable(M->getSymbolTable());
812 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
816 Out << "\nimplementation ; Functions:\n";
818 // Output all of the functions.
819 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
823 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
824 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
826 if (!GV->hasInitializer())
827 switch (GV->getLinkage()) {
828 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
829 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
830 default: Out << "external "; break;
833 switch (GV->getLinkage()) {
834 case GlobalValue::InternalLinkage: Out << "internal "; break;
835 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
836 case GlobalValue::WeakLinkage: Out << "weak "; break;
837 case GlobalValue::AppendingLinkage: Out << "appending "; break;
838 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
839 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
840 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
841 case GlobalValue::ExternalLinkage: break;
842 case GlobalValue::GhostLinkage:
843 llvm_cerr << "GhostLinkage not allowed in AsmWriter!\n";
847 Out << (GV->isConstant() ? "constant " : "global ");
848 printType(GV->getType()->getElementType());
850 if (GV->hasInitializer()) {
851 Constant* C = cast<Constant>(GV->getInitializer());
852 assert(C && "GlobalVar initializer isn't constant?");
853 writeOperand(GV->getInitializer(), false, isa<GlobalValue>(C));
856 if (GV->hasSection())
857 Out << ", section \"" << GV->getSection() << '"';
858 if (GV->getAlignment())
859 Out << ", align " << GV->getAlignment();
861 printInfoComment(*GV);
866 // printSymbolTable - Run through symbol table looking for constants
867 // and types. Emit their declarations.
868 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
871 for (SymbolTable::type_const_iterator TI = ST.type_begin();
872 TI != ST.type_end(); ++TI) {
873 Out << "\t" << getLLVMName(TI->first) << " = type ";
875 // Make sure we print out at least one level of the type structure, so
876 // that we do not get %FILE = type %FILE
878 printTypeAtLeastOneLevel(TI->second) << "\n";
881 // Print the constants, in type plane order.
882 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
883 PI != ST.plane_end(); ++PI) {
884 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
885 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
887 for (; VI != VE; ++VI) {
888 const Value* V = VI->second;
889 const Constant *CPV = dyn_cast<Constant>(V) ;
890 if (CPV && !isa<GlobalValue>(V)) {
898 /// printConstant - Print out a constant pool entry...
900 void AssemblyWriter::printConstant(const Constant *CPV) {
901 // Don't print out unnamed constants, they will be inlined
902 if (!CPV->hasName()) return;
905 Out << "\t" << getLLVMName(CPV->getName()) << " =";
907 // Write the value out now...
908 writeOperand(CPV, true, false);
910 printInfoComment(*CPV);
914 /// printFunction - Print all aspects of a function.
916 void AssemblyWriter::printFunction(const Function *F) {
917 // Print out the return type and name...
920 // Ensure that no local symbols conflict with global symbols.
921 const_cast<Function*>(F)->renameLocalSymbols();
923 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
926 switch (F->getLinkage()) {
927 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
928 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
929 default: Out << "declare ";
932 switch (F->getLinkage()) {
933 case GlobalValue::InternalLinkage: Out << "internal "; break;
934 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
935 case GlobalValue::WeakLinkage: Out << "weak "; break;
936 case GlobalValue::AppendingLinkage: Out << "appending "; break;
937 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
938 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
939 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
940 case GlobalValue::ExternalLinkage: break;
941 case GlobalValue::GhostLinkage:
942 llvm_cerr << "GhostLinkage not allowed in AsmWriter!\n";
946 // Print the calling convention.
947 switch (F->getCallingConv()) {
948 case CallingConv::C: break; // default
949 case CallingConv::CSRet: Out << "csretcc "; break;
950 case CallingConv::Fast: Out << "fastcc "; break;
951 case CallingConv::Cold: Out << "coldcc "; break;
952 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
953 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
954 default: Out << "cc" << F->getCallingConv() << " "; break;
957 printType(F->getReturnType()) << ' ';
958 if (!F->getName().empty())
959 Out << getLLVMName(F->getName());
963 Machine.incorporateFunction(F);
965 // Loop over the arguments, printing them...
966 const FunctionType *FT = F->getFunctionType();
968 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
972 // Finish printing arguments...
973 if (FT->isVarArg()) {
974 if (FT->getNumParams()) Out << ", ";
975 Out << "..."; // Output varargs portion of signature!
980 Out << " section \"" << F->getSection() << '"';
981 if (F->getAlignment())
982 Out << " align " << F->getAlignment();
984 if (F->isExternal()) {
989 // Output all of its basic blocks... for the function
990 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
996 Machine.purgeFunction();
999 /// printArgument - This member is called for every argument that is passed into
1000 /// the function. Simply print it out
1002 void AssemblyWriter::printArgument(const Argument *Arg) {
1003 // Insert commas as we go... the first arg doesn't get a comma
1004 if (Arg != Arg->getParent()->arg_begin()) Out << ", ";
1007 printType(Arg->getType());
1009 // Output name, if available...
1011 Out << ' ' << getLLVMName(Arg->getName());
1014 /// printBasicBlock - This member is called for each basic block in a method.
1016 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1017 if (BB->hasName()) { // Print out the label if it exists...
1018 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1019 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1020 Out << "\n; <label>:";
1021 int Slot = Machine.getSlot(BB);
1028 if (BB->getParent() == 0)
1029 Out << "\t\t; Error: Block without parent!";
1031 if (BB != &BB->getParent()->front()) { // Not the entry block?
1032 // Output predecessors for the block...
1034 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1037 Out << " No predecessors!";
1040 writeOperand(*PI, false, true);
1041 for (++PI; PI != PE; ++PI) {
1043 writeOperand(*PI, false, true);
1051 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1053 // Output all of the instructions in the basic block...
1054 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1055 printInstruction(*I);
1057 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1061 /// printInfoComment - Print a little comment after the instruction indicating
1062 /// which slot it occupies.
1064 void AssemblyWriter::printInfoComment(const Value &V) {
1065 if (V.getType() != Type::VoidTy) {
1067 printType(V.getType()) << '>';
1070 int SlotNum = Machine.getSlot(&V);
1074 Out << ':' << SlotNum; // Print out the def slot taken.
1076 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1080 // This member is called for each Instruction in a function..
1081 void AssemblyWriter::printInstruction(const Instruction &I) {
1082 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1086 // Print out name if it exists...
1088 Out << getLLVMName(I.getName()) << " = ";
1090 // If this is a volatile load or store, print out the volatile marker.
1091 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1092 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1094 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1095 // If this is a call, check if it's a tail call.
1099 // Print out the opcode...
1100 Out << I.getOpcodeName();
1102 // Print out the compare instruction predicates
1103 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1104 Out << " " << getPredicateText(FCI->getPredicate());
1105 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1106 Out << " " << getPredicateText(ICI->getPredicate());
1109 // Print out the type of the operands...
1110 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1112 // Special case conditional branches to swizzle the condition out to the front
1113 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1114 writeOperand(I.getOperand(2), true);
1116 writeOperand(Operand, true);
1118 writeOperand(I.getOperand(1), true);
1120 } else if (isa<SwitchInst>(I)) {
1121 // Special case switch statement to get formatting nice and correct...
1122 writeOperand(Operand , true); Out << ',';
1123 writeOperand(I.getOperand(1), true); Out << " [";
1125 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1127 writeOperand(I.getOperand(op ), true); Out << ',';
1128 writeOperand(I.getOperand(op+1), true);
1131 } else if (isa<PHINode>(I)) {
1133 printType(I.getType());
1136 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1137 if (op) Out << ", ";
1139 writeOperand(I.getOperand(op ), false); Out << ',';
1140 writeOperand(I.getOperand(op+1), false); Out << " ]";
1142 } else if (isa<ReturnInst>(I) && !Operand) {
1144 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1145 // Print the calling convention being used.
1146 switch (CI->getCallingConv()) {
1147 case CallingConv::C: break; // default
1148 case CallingConv::CSRet: Out << " csretcc"; break;
1149 case CallingConv::Fast: Out << " fastcc"; break;
1150 case CallingConv::Cold: Out << " coldcc"; break;
1151 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1152 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1153 default: Out << " cc" << CI->getCallingConv(); break;
1156 const PointerType *PTy = cast<PointerType>(Operand->getType());
1157 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1158 const Type *RetTy = FTy->getReturnType();
1160 // If possible, print out the short form of the call instruction. We can
1161 // only do this if the first argument is a pointer to a nonvararg function,
1162 // and if the return type is not a pointer to a function.
1164 if (!FTy->isVarArg() &&
1165 (!isa<PointerType>(RetTy) ||
1166 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1167 Out << ' '; printType(RetTy);
1168 writeOperand(Operand, false);
1170 writeOperand(Operand, true);
1173 if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true);
1174 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
1176 writeOperand(I.getOperand(op), true);
1180 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1181 const PointerType *PTy = cast<PointerType>(Operand->getType());
1182 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1183 const Type *RetTy = FTy->getReturnType();
1185 // Print the calling convention being used.
1186 switch (II->getCallingConv()) {
1187 case CallingConv::C: break; // default
1188 case CallingConv::CSRet: Out << " csretcc"; break;
1189 case CallingConv::Fast: Out << " fastcc"; break;
1190 case CallingConv::Cold: Out << " coldcc"; break;
1191 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1192 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1193 default: Out << " cc" << II->getCallingConv(); break;
1196 // If possible, print out the short form of the invoke instruction. We can
1197 // only do this if the first argument is a pointer to a nonvararg function,
1198 // and if the return type is not a pointer to a function.
1200 if (!FTy->isVarArg() &&
1201 (!isa<PointerType>(RetTy) ||
1202 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1203 Out << ' '; printType(RetTy);
1204 writeOperand(Operand, false);
1206 writeOperand(Operand, true);
1210 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1211 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1213 writeOperand(I.getOperand(op), true);
1216 Out << " )\n\t\t\tto";
1217 writeOperand(II->getNormalDest(), true);
1219 writeOperand(II->getUnwindDest(), true);
1221 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1223 printType(AI->getType()->getElementType());
1224 if (AI->isArrayAllocation()) {
1226 writeOperand(AI->getArraySize(), true);
1228 if (AI->getAlignment()) {
1229 Out << ", align " << AI->getAlignment();
1231 } else if (isa<CastInst>(I)) {
1232 if (Operand) writeOperand(Operand, true); // Work with broken code
1234 printType(I.getType());
1235 } else if (isa<VAArgInst>(I)) {
1236 if (Operand) writeOperand(Operand, true); // Work with broken code
1238 printType(I.getType());
1239 } else if (Operand) { // Print the normal way...
1241 // PrintAllTypes - Instructions who have operands of all the same type
1242 // omit the type from all but the first operand. If the instruction has
1243 // different type operands (for example br), then they are all printed.
1244 bool PrintAllTypes = false;
1245 const Type *TheType = Operand->getType();
1247 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1248 // types even if all operands are bools.
1249 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1250 isa<ShuffleVectorInst>(I)) {
1251 PrintAllTypes = true;
1253 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1254 Operand = I.getOperand(i);
1255 if (Operand->getType() != TheType) {
1256 PrintAllTypes = true; // We have differing types! Print them all!
1262 if (!PrintAllTypes) {
1267 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1269 writeOperand(I.getOperand(i), PrintAllTypes);
1273 printInfoComment(I);
1278 //===----------------------------------------------------------------------===//
1279 // External Interface declarations
1280 //===----------------------------------------------------------------------===//
1282 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1283 SlotMachine SlotTable(this);
1284 AssemblyWriter W(o, SlotTable, this, AAW);
1288 void GlobalVariable::print(std::ostream &o) const {
1289 SlotMachine SlotTable(getParent());
1290 AssemblyWriter W(o, SlotTable, getParent(), 0);
1294 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1295 SlotMachine SlotTable(getParent());
1296 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1301 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1302 WriteAsOperand(o, this, true, true, 0);
1305 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1306 SlotMachine SlotTable(getParent());
1307 AssemblyWriter W(o, SlotTable,
1308 getParent() ? getParent()->getParent() : 0, AAW);
1312 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1313 const Function *F = getParent() ? getParent()->getParent() : 0;
1314 SlotMachine SlotTable(F);
1315 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1320 void Constant::print(std::ostream &o) const {
1321 if (this == 0) { o << "<null> constant value\n"; return; }
1323 o << ' ' << getType()->getDescription() << ' ';
1325 std::map<const Type *, std::string> TypeTable;
1326 WriteConstantInt(o, this, false, TypeTable, 0);
1329 void Type::print(std::ostream &o) const {
1333 o << getDescription();
1336 void Argument::print(std::ostream &o) const {
1337 WriteAsOperand(o, this, true, true,
1338 getParent() ? getParent()->getParent() : 0);
1341 // Value::dump - allow easy printing of Values from the debugger.
1342 // Located here because so much of the needed functionality is here.
1343 void Value::dump() const { print(std::cerr); llvm_cerr << '\n'; }
1345 // Type::dump - allow easy printing of Values from the debugger.
1346 // Located here because so much of the needed functionality is here.
1347 void Type::dump() const { print(std::cerr); llvm_cerr << '\n'; }
1349 //===----------------------------------------------------------------------===//
1350 // CachedWriter Class Implementation
1351 //===----------------------------------------------------------------------===//
1353 void CachedWriter::setModule(const Module *M) {
1354 delete SC; delete AW;
1356 SC = new SlotMachine(M);
1357 AW = new AssemblyWriter(Out, *SC, M, 0);
1363 CachedWriter::~CachedWriter() {
1368 CachedWriter &CachedWriter::operator<<(const Value &V) {
1369 assert(AW && SC && "CachedWriter does not have a current module!");
1370 if (const Instruction *I = dyn_cast<Instruction>(&V))
1372 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(&V))
1374 else if (const Function *F = dyn_cast<Function>(&V))
1376 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(&V))
1379 AW->writeOperand(&V, true, true);
1383 CachedWriter& CachedWriter::operator<<(const Type &Ty) {
1384 if (SymbolicTypes) {
1385 const Module *M = AW->getModule();
1386 if (M) WriteTypeSymbolic(Out, &Ty, M);
1393 //===----------------------------------------------------------------------===//
1394 //===-- SlotMachine Implementation
1395 //===----------------------------------------------------------------------===//
1398 #define SC_DEBUG(X) llvm_cerr << X
1403 // Module level constructor. Causes the contents of the Module (sans functions)
1404 // to be added to the slot table.
1405 SlotMachine::SlotMachine(const Module *M)
1406 : TheModule(M) ///< Saved for lazy initialization.
1408 , FunctionProcessed(false)
1412 // Function level constructor. Causes the contents of the Module and the one
1413 // function provided to be added to the slot table.
1414 SlotMachine::SlotMachine(const Function *F)
1415 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1416 , TheFunction(F) ///< Saved for lazy initialization
1417 , FunctionProcessed(false)
1421 inline void SlotMachine::initialize(void) {
1424 TheModule = 0; ///< Prevent re-processing next time we're called.
1426 if (TheFunction && !FunctionProcessed)
1430 // Iterate through all the global variables, functions, and global
1431 // variable initializers and create slots for them.
1432 void SlotMachine::processModule() {
1433 SC_DEBUG("begin processModule!\n");
1435 // Add all of the unnamed global variables to the value table.
1436 for (Module::const_global_iterator I = TheModule->global_begin(),
1437 E = TheModule->global_end(); I != E; ++I)
1441 // Add all the unnamed functions to the table.
1442 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1447 SC_DEBUG("end processModule!\n");
1451 // Process the arguments, basic blocks, and instructions of a function.
1452 void SlotMachine::processFunction() {
1453 SC_DEBUG("begin processFunction!\n");
1455 // Add all the function arguments with no names.
1456 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1457 AE = TheFunction->arg_end(); AI != AE; ++AI)
1459 getOrCreateSlot(AI);
1461 SC_DEBUG("Inserting Instructions:\n");
1463 // Add all of the basic blocks and instructions with no names.
1464 for (Function::const_iterator BB = TheFunction->begin(),
1465 E = TheFunction->end(); BB != E; ++BB) {
1467 getOrCreateSlot(BB);
1468 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1469 if (I->getType() != Type::VoidTy && !I->hasName())
1473 FunctionProcessed = true;
1475 SC_DEBUG("end processFunction!\n");
1478 /// Clean up after incorporating a function. This is the only way to get out of
1479 /// the function incorporation state that affects the
1480 /// getSlot/getOrCreateSlot lock. Function incorporation state is indicated
1481 /// by TheFunction != 0.
1482 void SlotMachine::purgeFunction() {
1483 SC_DEBUG("begin purgeFunction!\n");
1484 fMap.clear(); // Simply discard the function level map
1486 FunctionProcessed = false;
1487 SC_DEBUG("end purgeFunction!\n");
1490 /// Get the slot number for a value. This function will assert if you
1491 /// ask for a Value that hasn't previously been inserted with getOrCreateSlot.
1492 /// Types are forbidden because Type does not inherit from Value (any more).
1493 int SlotMachine::getSlot(const Value *V) {
1494 assert(V && "Can't get slot for null Value");
1495 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1496 "Can't insert a non-GlobalValue Constant into SlotMachine");
1498 // Check for uninitialized state and do lazy initialization
1501 // Get the type of the value
1502 const Type* VTy = V->getType();
1504 // Find the type plane in the module map
1505 TypedPlanes::const_iterator MI = mMap.find(VTy);
1508 // Lookup the type in the function map too
1509 TypedPlanes::const_iterator FI = fMap.find(VTy);
1510 // If there is a corresponding type plane in the function map
1511 if (FI != fMap.end()) {
1512 // Lookup the Value in the function map
1513 ValueMap::const_iterator FVI = FI->second.map.find(V);
1514 // If the value doesn't exist in the function map
1515 if (FVI == FI->second.map.end()) {
1516 // Look up the value in the module map.
1517 if (MI == mMap.end()) return -1;
1518 ValueMap::const_iterator MVI = MI->second.map.find(V);
1519 // If we didn't find it, it wasn't inserted
1520 if (MVI == MI->second.map.end()) return -1;
1521 assert(MVI != MI->second.map.end() && "Value not found");
1522 // We found it only at the module level
1525 // else the value exists in the function map
1527 // Return the slot number as the module's contribution to
1528 // the type plane plus the index in the function's contribution
1529 // to the type plane.
1530 if (MI != mMap.end())
1531 return MI->second.next_slot + FVI->second;
1538 // N.B. Can get here only if either !TheFunction or the function doesn't
1539 // have a corresponding type plane for the Value
1541 // Make sure the type plane exists
1542 if (MI == mMap.end()) return -1;
1543 // Lookup the value in the module's map
1544 ValueMap::const_iterator MVI = MI->second.map.find(V);
1545 // Make sure we found it.
1546 if (MVI == MI->second.map.end()) return -1;
1552 // Create a new slot, or return the existing slot if it is already
1553 // inserted. Note that the logic here parallels getSlot but instead
1554 // of asserting when the Value* isn't found, it inserts the value.
1555 unsigned SlotMachine::getOrCreateSlot(const Value *V) {
1556 const Type* VTy = V->getType();
1557 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1558 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1559 "Can't insert a non-GlobalValue Constant into SlotMachine");
1561 // Look up the type plane for the Value's type from the module map
1562 TypedPlanes::const_iterator MI = mMap.find(VTy);
1565 // Get the type plane for the Value's type from the function map
1566 TypedPlanes::const_iterator FI = fMap.find(VTy);
1567 // If there is a corresponding type plane in the function map
1568 if (FI != fMap.end()) {
1569 // Lookup the Value in the function map
1570 ValueMap::const_iterator FVI = FI->second.map.find(V);
1571 // If the value doesn't exist in the function map
1572 if (FVI == FI->second.map.end()) {
1573 // If there is no corresponding type plane in the module map
1574 if (MI == mMap.end())
1575 return insertValue(V);
1576 // Look up the value in the module map
1577 ValueMap::const_iterator MVI = MI->second.map.find(V);
1578 // If we didn't find it, it wasn't inserted
1579 if (MVI == MI->second.map.end())
1580 return insertValue(V);
1582 // We found it only at the module level
1585 // else the value exists in the function map
1587 if (MI == mMap.end())
1590 // Return the slot number as the module's contribution to
1591 // the type plane plus the index in the function's contribution
1592 // to the type plane.
1593 return MI->second.next_slot + FVI->second;
1596 // else there is not a corresponding type plane in the function map
1598 // If the type plane doesn't exists at the module level
1599 if (MI == mMap.end()) {
1600 return insertValue(V);
1601 // else type plane exists at the module level, examine it
1603 // Look up the value in the module's map
1604 ValueMap::const_iterator MVI = MI->second.map.find(V);
1605 // If we didn't find it there either
1606 if (MVI == MI->second.map.end())
1607 // Return the slot number as the module's contribution to
1608 // the type plane plus the index of the function map insertion.
1609 return MI->second.next_slot + insertValue(V);
1616 // N.B. Can only get here if TheFunction == 0
1618 // If the module map's type plane is not for the Value's type
1619 if (MI != mMap.end()) {
1620 // Lookup the value in the module's map
1621 ValueMap::const_iterator MVI = MI->second.map.find(V);
1622 if (MVI != MI->second.map.end())
1626 return insertValue(V);
1630 // Low level insert function. Minimal checking is done. This
1631 // function is just for the convenience of getOrCreateSlot (above).
1632 unsigned SlotMachine::insertValue(const Value *V) {
1633 assert(V && "Can't insert a null Value into SlotMachine!");
1634 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1635 "Can't insert a non-GlobalValue Constant into SlotMachine");
1636 assert(V->getType() != Type::VoidTy && !V->hasName());
1638 const Type *VTy = V->getType();
1639 unsigned DestSlot = 0;
1642 TypedPlanes::iterator I = fMap.find(VTy);
1643 if (I == fMap.end())
1644 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1645 DestSlot = I->second.map[V] = I->second.next_slot++;
1647 TypedPlanes::iterator I = mMap.find(VTy);
1648 if (I == mMap.end())
1649 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1650 DestSlot = I->second.map[V] = I->second.next_slot++;
1653 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1655 // G = Global, F = Function, o = other
1656 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 'o')));