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/ADT/StringExtras.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/Streams.h"
38 // Make virtual table appear in this compilation unit.
39 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
41 /// This class provides computation of slot numbers for LLVM Assembly writing.
42 /// @brief LLVM Assembly Writing Slot Computation.
49 /// @brief A mapping of Values to slot numbers
50 typedef std::map<const Value*, unsigned> ValueMap;
52 /// @brief A plane with next slot number and ValueMap
54 unsigned next_slot; ///< The next slot number to use
55 ValueMap map; ///< The map of Value* -> unsigned
56 ValuePlane() { next_slot = 0; } ///< Make sure we start at 0
59 /// @brief The map of planes by Type
60 typedef std::map<const Type*, ValuePlane> TypedPlanes;
63 /// @name Constructors
66 /// @brief Construct from a module
67 SlotMachine(const Module *M);
69 /// @brief Construct from a function, starting out in incorp state.
70 SlotMachine(const Function *F);
76 /// Return the slot number of the specified value in it's type
77 /// plane. Its an error to ask for something not in the SlotMachine.
78 /// Its an error to ask for a Type*
79 int getSlot(const Value *V);
85 /// If you'd like to deal with a function instead of just a module, use
86 /// this method to get its data into the SlotMachine.
87 void incorporateFunction(const Function *F) {
89 FunctionProcessed = false;
92 /// After calling incorporateFunction, use this method to remove the
93 /// most recently incorporated function from the SlotMachine. This
94 /// will reset the state of the machine back to just the module contents.
98 /// @name Implementation Details
101 /// This function does the actual initialization.
102 inline void initialize();
104 /// Values can be crammed into here at will. If they haven't
105 /// been inserted already, they get inserted, otherwise they are ignored.
106 /// Either way, the slot number for the Value* is returned.
107 unsigned getOrCreateSlot(const Value *V);
109 /// Insert a value into the value table. Return the slot number
110 /// that it now occupies. BadThings(TM) will happen if you insert a
111 /// Value that's already been inserted.
112 unsigned insertValue(const Value *V);
114 /// Add all of the module level global variables (and their initializers)
115 /// and function declarations, but not the contents of those functions.
116 void processModule();
118 /// Add all of the functions arguments, basic blocks, and instructions
119 void processFunction();
121 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
122 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
129 /// @brief The module for which we are holding slot numbers
130 const Module* TheModule;
132 /// @brief The function for which we are holding slot numbers
133 const Function* TheFunction;
134 bool FunctionProcessed;
136 /// @brief The TypePlanes map for the module level data
139 /// @brief The TypePlanes map for the function level data
146 } // end namespace llvm
148 static RegisterPass<PrintModulePass>
149 X("printm", "Print module to stderr");
150 static RegisterPass<PrintFunctionPass>
151 Y("print","Print function to stderr");
153 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
154 std::map<const Type *, std::string> &TypeTable,
155 SlotMachine *Machine);
157 static const Module *getModuleFromVal(const Value *V) {
158 if (const Argument *MA = dyn_cast<Argument>(V))
159 return MA->getParent() ? MA->getParent()->getParent() : 0;
160 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
161 return BB->getParent() ? BB->getParent()->getParent() : 0;
162 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
163 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
164 return M ? M->getParent() : 0;
165 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
166 return GV->getParent();
170 static SlotMachine *createSlotMachine(const Value *V) {
171 if (const Argument *FA = dyn_cast<Argument>(V)) {
172 return new SlotMachine(FA->getParent());
173 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
174 return new SlotMachine(I->getParent()->getParent());
175 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
176 return new SlotMachine(BB->getParent());
177 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
178 return new SlotMachine(GV->getParent());
179 } else if (const Function *Func = dyn_cast<Function>(V)) {
180 return new SlotMachine(Func);
185 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
186 // prefixed with % (if the string only contains simple characters) or is
187 // surrounded with ""'s (if it has special chars in it).
188 static std::string getLLVMName(const std::string &Name,
189 bool prefixName = true) {
190 assert(!Name.empty() && "Cannot get empty name!");
192 // First character cannot start with a number...
193 if (Name[0] >= '0' && Name[0] <= '9')
194 return "\"" + Name + "\"";
196 // Scan to see if we have any characters that are not on the "white list"
197 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
199 assert(C != '"' && "Illegal character in LLVM value name!");
200 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
201 C != '-' && C != '.' && C != '_')
202 return "\"" + Name + "\"";
205 // If we get here, then the identifier is legal to use as a "VarID".
213 /// fillTypeNameTable - If the module has a symbol table, take all global types
214 /// and stuff their names into the TypeNames map.
216 static void fillTypeNameTable(const Module *M,
217 std::map<const Type *, std::string> &TypeNames) {
219 const SymbolTable &ST = M->getSymbolTable();
220 SymbolTable::type_const_iterator TI = ST.type_begin();
221 for (; TI != ST.type_end(); ++TI) {
222 // As a heuristic, don't insert pointer to primitive types, because
223 // they are used too often to have a single useful name.
225 const Type *Ty = cast<Type>(TI->second);
226 if (!isa<PointerType>(Ty) ||
227 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
228 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
229 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
235 static void calcTypeName(const Type *Ty,
236 std::vector<const Type *> &TypeStack,
237 std::map<const Type *, std::string> &TypeNames,
238 std::string & Result){
239 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
240 Result += Ty->getDescription(); // Base case
244 // Check to see if the type is named.
245 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
246 if (I != TypeNames.end()) {
251 if (isa<OpaqueType>(Ty)) {
256 // Check to see if the Type is already on the stack...
257 unsigned Slot = 0, CurSize = TypeStack.size();
258 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
260 // This is another base case for the recursion. In this case, we know
261 // that we have looped back to a type that we have previously visited.
262 // Generate the appropriate upreference to handle this.
263 if (Slot < CurSize) {
264 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
268 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
270 switch (Ty->getTypeID()) {
271 case Type::FunctionTyID: {
272 const FunctionType *FTy = cast<FunctionType>(Ty);
273 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
275 for (FunctionType::param_iterator I = FTy->param_begin(),
276 E = FTy->param_end(); I != E; ++I) {
277 if (I != FTy->param_begin())
279 calcTypeName(*I, TypeStack, TypeNames, Result);
281 if (FTy->isVarArg()) {
282 if (FTy->getNumParams()) Result += ", ";
288 case Type::StructTyID: {
289 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);
304 case Type::PointerTyID:
305 calcTypeName(cast<PointerType>(Ty)->getElementType(),
306 TypeStack, TypeNames, Result);
309 case Type::ArrayTyID: {
310 const ArrayType *ATy = cast<ArrayType>(Ty);
311 Result += "[" + utostr(ATy->getNumElements()) + " x ";
312 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
316 case Type::PackedTyID: {
317 const PackedType *PTy = cast<PackedType>(Ty);
318 Result += "<" + utostr(PTy->getNumElements()) + " x ";
319 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
323 case Type::OpaqueTyID:
327 Result += "<unrecognized-type>";
331 TypeStack.pop_back(); // Remove self from stack...
335 /// printTypeInt - The internal guts of printing out a type that has a
336 /// potentially named portion.
338 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
339 std::map<const Type *, std::string> &TypeNames) {
340 // Primitive types always print out their description, regardless of whether
341 // they have been named or not.
343 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
344 return Out << Ty->getDescription();
346 // Check to see if the type is named.
347 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
348 if (I != TypeNames.end()) return Out << I->second;
350 // Otherwise we have a type that has not been named but is a derived type.
351 // Carefully recurse the type hierarchy to print out any contained symbolic
354 std::vector<const Type *> TypeStack;
355 std::string TypeName;
356 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
357 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
358 return (Out << TypeName);
362 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
363 /// type, iff there is an entry in the modules symbol table for the specified
364 /// type or one of it's component types. This is slower than a simple x << Type
366 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
370 // If they want us to print out a type, but there is no context, we can't
371 // print it symbolically.
373 return Out << Ty->getDescription();
375 std::map<const Type *, std::string> TypeNames;
376 fillTypeNameTable(M, TypeNames);
377 return printTypeInt(Out, Ty, TypeNames);
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,
430 std::map<const Type *, std::string> &TypeTable,
431 SlotMachine *Machine) {
432 const int IndentSize = 4;
433 static std::string Indent = "\n";
434 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
435 Out << (CB->getValue() ? "true" : "false");
436 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
437 Out << CI->getSExtValue();
438 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
439 // We would like to output the FP constant value in exponential notation,
440 // but we cannot do this if doing so will lose precision. Check here to
441 // make sure that we only output it in exponential format if we can parse
442 // the value back and get the same value.
444 std::string StrVal = ftostr(CFP->getValue());
446 // Check to make sure that the stringized number is not some string like
447 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
448 // the string matches the "[-+]?[0-9]" regex.
450 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
451 ((StrVal[0] == '-' || StrVal[0] == '+') &&
452 (StrVal[1] >= '0' && StrVal[1] <= '9')))
453 // Reparse stringized version!
454 if (atof(StrVal.c_str()) == CFP->getValue()) {
459 // Otherwise we could not reparse it to exactly the same value, so we must
460 // output the string in hexadecimal format!
461 assert(sizeof(double) == sizeof(uint64_t) &&
462 "assuming that double is 64 bits!");
463 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
465 } else if (isa<ConstantAggregateZero>(CV)) {
466 Out << "zeroinitializer";
467 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
468 // As a special case, print the array as a string if it is an array of
469 // ubytes or an array of sbytes with positive values.
471 const Type *ETy = CA->getType()->getElementType();
472 if (CA->isString()) {
474 PrintEscapedString(CA->getAsString(), Out);
477 } else { // Cannot output in string format...
479 if (CA->getNumOperands()) {
481 printTypeInt(Out, ETy, TypeTable);
482 WriteAsOperandInternal(Out, CA->getOperand(0),
484 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
486 printTypeInt(Out, ETy, TypeTable);
487 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
492 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
494 unsigned N = CS->getNumOperands();
497 Indent += std::string(IndentSize, ' ');
502 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
504 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
506 for (unsigned i = 1; i < N; i++) {
508 if (N > 2) Out << Indent;
509 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
511 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
513 if (N > 2) Indent.resize(Indent.size() - IndentSize);
517 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
518 const Type *ETy = CP->getType()->getElementType();
519 assert(CP->getNumOperands() > 0 &&
520 "Number of operands for a PackedConst must be > 0");
523 printTypeInt(Out, ETy, TypeTable);
524 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
525 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
527 printTypeInt(Out, ETy, TypeTable);
528 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
531 } else if (isa<ConstantPointerNull>(CV)) {
534 } else if (isa<UndefValue>(CV)) {
537 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
538 Out << CE->getOpcodeName();
540 Out << " " << getPredicateText(CE->getPredicate());
543 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
544 printTypeInt(Out, (*OI)->getType(), TypeTable);
545 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
546 if (OI+1 != CE->op_end())
552 printTypeInt(Out, CE->getType(), TypeTable);
558 Out << "<placeholder or erroneous Constant>";
563 /// WriteAsOperand - Write the name of the specified value out to the specified
564 /// ostream. This can be useful when you just want to print int %reg126, not
565 /// the whole instruction that generated it.
567 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
568 std::map<const Type*, std::string> &TypeTable,
569 SlotMachine *Machine) {
572 Out << getLLVMName(V->getName());
574 const Constant *CV = dyn_cast<Constant>(V);
575 if (CV && !isa<GlobalValue>(CV)) {
576 WriteConstantInt(Out, CV, TypeTable, Machine);
577 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
579 if (IA->hasSideEffects())
580 Out << "sideeffect ";
582 PrintEscapedString(IA->getAsmString(), Out);
584 PrintEscapedString(IA->getConstraintString(), Out);
589 Slot = Machine->getSlot(V);
591 Machine = createSlotMachine(V);
593 Slot = Machine->getSlot(V);
606 /// WriteAsOperand - Write the name of the specified value out to the specified
607 /// ostream. This can be useful when you just want to print int %reg126, not
608 /// the whole instruction that generated it.
610 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
611 bool PrintType, const Module *Context) {
612 std::map<const Type *, std::string> TypeNames;
613 if (Context == 0) Context = getModuleFromVal(V);
616 fillTypeNameTable(Context, TypeNames);
619 printTypeInt(Out, V->getType(), TypeNames);
621 WriteAsOperandInternal(Out, V, TypeNames, 0);
628 class AssemblyWriter {
630 SlotMachine &Machine;
631 const Module *TheModule;
632 std::map<const Type *, std::string> TypeNames;
633 AssemblyAnnotationWriter *AnnotationWriter;
635 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
636 AssemblyAnnotationWriter *AAW)
637 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
639 // If the module has a symbol table, take all global types and stuff their
640 // names into the TypeNames map.
642 fillTypeNameTable(M, TypeNames);
645 inline void write(const Module *M) { printModule(M); }
646 inline void write(const GlobalVariable *G) { printGlobal(G); }
647 inline void write(const Function *F) { printFunction(F); }
648 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
649 inline void write(const Instruction *I) { printInstruction(*I); }
650 inline void write(const Constant *CPV) { printConstant(CPV); }
651 inline void write(const Type *Ty) { printType(Ty); }
653 void writeOperand(const Value *Op, bool PrintType);
655 const Module* getModule() { return TheModule; }
658 void printModule(const Module *M);
659 void printSymbolTable(const SymbolTable &ST);
660 void printConstant(const Constant *CPV);
661 void printGlobal(const GlobalVariable *GV);
662 void printFunction(const Function *F);
663 void printArgument(const Argument *FA);
664 void printBasicBlock(const BasicBlock *BB);
665 void printInstruction(const Instruction &I);
667 // printType - Go to extreme measures to attempt to print out a short,
668 // symbolic version of a type name.
670 std::ostream &printType(const Type *Ty) {
671 return printTypeInt(Out, Ty, TypeNames);
674 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
675 // without considering any symbolic types that we may have equal to it.
677 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
679 // printInfoComment - Print a little comment after the instruction indicating
680 // which slot it occupies.
681 void printInfoComment(const Value &V);
683 } // end of llvm namespace
685 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
686 /// without considering any symbolic types that we may have equal to it.
688 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
689 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
690 printType(FTy->getReturnType()) << " (";
691 for (FunctionType::param_iterator I = FTy->param_begin(),
692 E = FTy->param_end(); I != E; ++I) {
693 if (I != FTy->param_begin())
697 if (FTy->isVarArg()) {
698 if (FTy->getNumParams()) Out << ", ";
702 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
706 for (StructType::element_iterator I = STy->element_begin(),
707 E = STy->element_end(); I != E; ++I) {
708 if (I != STy->element_begin())
715 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
716 printType(PTy->getElementType()) << '*';
717 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
718 Out << '[' << ATy->getNumElements() << " x ";
719 printType(ATy->getElementType()) << ']';
720 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
721 Out << '<' << PTy->getNumElements() << " x ";
722 printType(PTy->getElementType()) << '>';
724 else if (isa<OpaqueType>(Ty)) {
727 if (!Ty->isPrimitiveType())
728 Out << "<unknown derived type>";
735 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
737 Out << "<null operand!>";
739 if (PrintType) { Out << ' '; printType(Operand->getType()); }
740 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
745 void AssemblyWriter::printModule(const Module *M) {
746 if (!M->getModuleIdentifier().empty() &&
747 // Don't print the ID if it will start a new line (which would
748 // require a comment char before it).
749 M->getModuleIdentifier().find('\n') == std::string::npos)
750 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
752 if (!M->getDataLayout().empty())
753 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
755 switch (M->getEndianness()) {
756 case Module::LittleEndian: Out << "target endian = little\n"; break;
757 case Module::BigEndian: Out << "target endian = big\n"; break;
758 case Module::AnyEndianness: break;
760 switch (M->getPointerSize()) {
761 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
762 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
763 case Module::AnyPointerSize: break;
765 if (!M->getTargetTriple().empty())
766 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
768 if (!M->getModuleInlineAsm().empty()) {
769 // Split the string into lines, to make it easier to read the .ll file.
770 std::string Asm = M->getModuleInlineAsm();
772 size_t NewLine = Asm.find_first_of('\n', CurPos);
773 while (NewLine != std::string::npos) {
774 // We found a newline, print the portion of the asm string from the
775 // last newline up to this newline.
776 Out << "module asm \"";
777 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
781 NewLine = Asm.find_first_of('\n', CurPos);
783 Out << "module asm \"";
784 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
788 // Loop over the dependent libraries and emit them.
789 Module::lib_iterator LI = M->lib_begin();
790 Module::lib_iterator LE = M->lib_end();
792 Out << "deplibs = [ ";
794 Out << '"' << *LI << '"';
802 // Loop over the symbol table, emitting all named constants.
803 printSymbolTable(M->getSymbolTable());
805 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
809 Out << "\nimplementation ; Functions:\n";
811 // Output all of the functions.
812 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
816 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
817 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
819 if (!GV->hasInitializer())
820 switch (GV->getLinkage()) {
821 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
822 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
823 default: Out << "external "; break;
826 switch (GV->getLinkage()) {
827 case GlobalValue::InternalLinkage: Out << "internal "; break;
828 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
829 case GlobalValue::WeakLinkage: Out << "weak "; break;
830 case GlobalValue::AppendingLinkage: Out << "appending "; break;
831 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
832 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
833 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
834 case GlobalValue::ExternalLinkage: break;
835 case GlobalValue::GhostLinkage:
836 cerr << "GhostLinkage not allowed in AsmWriter!\n";
840 Out << (GV->isConstant() ? "constant " : "global ");
841 printType(GV->getType()->getElementType());
843 if (GV->hasInitializer()) {
844 Constant* C = cast<Constant>(GV->getInitializer());
845 assert(C && "GlobalVar initializer isn't constant?");
846 writeOperand(GV->getInitializer(), false);
849 if (GV->hasSection())
850 Out << ", section \"" << GV->getSection() << '"';
851 if (GV->getAlignment())
852 Out << ", align " << GV->getAlignment();
854 printInfoComment(*GV);
859 // printSymbolTable - Run through symbol table looking for constants
860 // and types. Emit their declarations.
861 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
864 for (SymbolTable::type_const_iterator TI = ST.type_begin();
865 TI != ST.type_end(); ++TI) {
866 Out << "\t" << getLLVMName(TI->first) << " = type ";
868 // Make sure we print out at least one level of the type structure, so
869 // that we do not get %FILE = type %FILE
871 printTypeAtLeastOneLevel(TI->second) << "\n";
874 // Print the constants, in type plane order.
875 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
876 PI != ST.plane_end(); ++PI) {
877 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
878 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
880 for (; VI != VE; ++VI) {
881 const Value* V = VI->second;
882 const Constant *CPV = dyn_cast<Constant>(V) ;
883 if (CPV && !isa<GlobalValue>(V)) {
891 /// printConstant - Print out a constant pool entry...
893 void AssemblyWriter::printConstant(const Constant *CPV) {
894 // Don't print out unnamed constants, they will be inlined
895 if (!CPV->hasName()) return;
898 Out << "\t" << getLLVMName(CPV->getName()) << " =";
900 // Write the value out now.
901 writeOperand(CPV, true);
903 printInfoComment(*CPV);
907 /// printFunction - Print all aspects of a function.
909 void AssemblyWriter::printFunction(const Function *F) {
910 // Print out the return type and name...
913 // Ensure that no local symbols conflict with global symbols.
914 const_cast<Function*>(F)->renameLocalSymbols();
916 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
919 switch (F->getLinkage()) {
920 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
921 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
922 default: Out << "declare ";
925 switch (F->getLinkage()) {
926 case GlobalValue::InternalLinkage: Out << "internal "; break;
927 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
928 case GlobalValue::WeakLinkage: Out << "weak "; break;
929 case GlobalValue::AppendingLinkage: Out << "appending "; break;
930 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
931 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
932 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
933 case GlobalValue::ExternalLinkage: break;
934 case GlobalValue::GhostLinkage:
935 cerr << "GhostLinkage not allowed in AsmWriter!\n";
939 // Print the calling convention.
940 switch (F->getCallingConv()) {
941 case CallingConv::C: break; // default
942 case CallingConv::CSRet: Out << "csretcc "; break;
943 case CallingConv::Fast: Out << "fastcc "; break;
944 case CallingConv::Cold: Out << "coldcc "; break;
945 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
946 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
947 default: Out << "cc" << F->getCallingConv() << " "; break;
950 printType(F->getReturnType()) << ' ';
951 if (!F->getName().empty())
952 Out << getLLVMName(F->getName());
956 Machine.incorporateFunction(F);
958 // Loop over the arguments, printing them...
959 const FunctionType *FT = F->getFunctionType();
961 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
965 // Finish printing arguments...
966 if (FT->isVarArg()) {
967 if (FT->getNumParams()) Out << ", ";
968 Out << "..."; // Output varargs portion of signature!
973 Out << " section \"" << F->getSection() << '"';
974 if (F->getAlignment())
975 Out << " align " << F->getAlignment();
977 if (F->isExternal()) {
982 // Output all of its basic blocks... for the function
983 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
989 Machine.purgeFunction();
992 /// printArgument - This member is called for every argument that is passed into
993 /// the function. Simply print it out
995 void AssemblyWriter::printArgument(const Argument *Arg) {
996 // Insert commas as we go... the first arg doesn't get a comma
997 if (Arg != Arg->getParent()->arg_begin()) Out << ", ";
1000 printType(Arg->getType());
1002 // Output name, if available...
1004 Out << ' ' << getLLVMName(Arg->getName());
1007 /// printBasicBlock - This member is called for each basic block in a method.
1009 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1010 if (BB->hasName()) { // Print out the label if it exists...
1011 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1012 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1013 Out << "\n; <label>:";
1014 int Slot = Machine.getSlot(BB);
1021 if (BB->getParent() == 0)
1022 Out << "\t\t; Error: Block without parent!";
1024 if (BB != &BB->getParent()->front()) { // Not the entry block?
1025 // Output predecessors for the block...
1027 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1030 Out << " No predecessors!";
1033 writeOperand(*PI, false);
1034 for (++PI; PI != PE; ++PI) {
1036 writeOperand(*PI, false);
1044 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1046 // Output all of the instructions in the basic block...
1047 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1048 printInstruction(*I);
1050 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1054 /// printInfoComment - Print a little comment after the instruction indicating
1055 /// which slot it occupies.
1057 void AssemblyWriter::printInfoComment(const Value &V) {
1058 if (V.getType() != Type::VoidTy) {
1060 printType(V.getType()) << '>';
1063 int SlotNum = Machine.getSlot(&V);
1067 Out << ':' << SlotNum; // Print out the def slot taken.
1069 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1073 // This member is called for each Instruction in a function..
1074 void AssemblyWriter::printInstruction(const Instruction &I) {
1075 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1079 // Print out name if it exists...
1081 Out << getLLVMName(I.getName()) << " = ";
1083 // If this is a volatile load or store, print out the volatile marker.
1084 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1085 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1087 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1088 // If this is a call, check if it's a tail call.
1092 // Print out the opcode...
1093 Out << I.getOpcodeName();
1095 // Print out the compare instruction predicates
1096 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1097 Out << " " << getPredicateText(FCI->getPredicate());
1098 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1099 Out << " " << getPredicateText(ICI->getPredicate());
1102 // Print out the type of the operands...
1103 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1105 // Special case conditional branches to swizzle the condition out to the front
1106 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1107 writeOperand(I.getOperand(2), true);
1109 writeOperand(Operand, true);
1111 writeOperand(I.getOperand(1), true);
1113 } else if (isa<SwitchInst>(I)) {
1114 // Special case switch statement to get formatting nice and correct...
1115 writeOperand(Operand , true); Out << ',';
1116 writeOperand(I.getOperand(1), true); Out << " [";
1118 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1120 writeOperand(I.getOperand(op ), true); Out << ',';
1121 writeOperand(I.getOperand(op+1), true);
1124 } else if (isa<PHINode>(I)) {
1126 printType(I.getType());
1129 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1130 if (op) Out << ", ";
1132 writeOperand(I.getOperand(op ), false); Out << ',';
1133 writeOperand(I.getOperand(op+1), false); Out << " ]";
1135 } else if (isa<ReturnInst>(I) && !Operand) {
1137 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1138 // Print the calling convention being used.
1139 switch (CI->getCallingConv()) {
1140 case CallingConv::C: break; // default
1141 case CallingConv::CSRet: Out << " csretcc"; break;
1142 case CallingConv::Fast: Out << " fastcc"; break;
1143 case CallingConv::Cold: Out << " coldcc"; break;
1144 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1145 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1146 default: Out << " cc" << CI->getCallingConv(); break;
1149 const PointerType *PTy = cast<PointerType>(Operand->getType());
1150 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1151 const Type *RetTy = FTy->getReturnType();
1153 // If possible, print out the short form of the call instruction. We can
1154 // only do this if the first argument is a pointer to a nonvararg function,
1155 // and if the return type is not a pointer to a function.
1157 if (!FTy->isVarArg() &&
1158 (!isa<PointerType>(RetTy) ||
1159 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1160 Out << ' '; printType(RetTy);
1161 writeOperand(Operand, false);
1163 writeOperand(Operand, true);
1166 if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true);
1167 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
1169 writeOperand(I.getOperand(op), true);
1173 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1174 const PointerType *PTy = cast<PointerType>(Operand->getType());
1175 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1176 const Type *RetTy = FTy->getReturnType();
1178 // Print the calling convention being used.
1179 switch (II->getCallingConv()) {
1180 case CallingConv::C: break; // default
1181 case CallingConv::CSRet: Out << " csretcc"; break;
1182 case CallingConv::Fast: Out << " fastcc"; break;
1183 case CallingConv::Cold: Out << " coldcc"; break;
1184 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1185 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1186 default: Out << " cc" << II->getCallingConv(); break;
1189 // If possible, print out the short form of the invoke instruction. We can
1190 // only do this if the first argument is a pointer to a nonvararg function,
1191 // and if the return type is not a pointer to a function.
1193 if (!FTy->isVarArg() &&
1194 (!isa<PointerType>(RetTy) ||
1195 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1196 Out << ' '; printType(RetTy);
1197 writeOperand(Operand, false);
1199 writeOperand(Operand, true);
1203 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1204 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1206 writeOperand(I.getOperand(op), true);
1209 Out << " )\n\t\t\tto";
1210 writeOperand(II->getNormalDest(), true);
1212 writeOperand(II->getUnwindDest(), true);
1214 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1216 printType(AI->getType()->getElementType());
1217 if (AI->isArrayAllocation()) {
1219 writeOperand(AI->getArraySize(), true);
1221 if (AI->getAlignment()) {
1222 Out << ", align " << AI->getAlignment();
1224 } else if (isa<CastInst>(I)) {
1225 if (Operand) writeOperand(Operand, true); // Work with broken code
1227 printType(I.getType());
1228 } else if (isa<VAArgInst>(I)) {
1229 if (Operand) writeOperand(Operand, true); // Work with broken code
1231 printType(I.getType());
1232 } else if (Operand) { // Print the normal way...
1234 // PrintAllTypes - Instructions who have operands of all the same type
1235 // omit the type from all but the first operand. If the instruction has
1236 // different type operands (for example br), then they are all printed.
1237 bool PrintAllTypes = false;
1238 const Type *TheType = Operand->getType();
1240 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1241 // types even if all operands are bools.
1242 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1243 isa<ShuffleVectorInst>(I)) {
1244 PrintAllTypes = true;
1246 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1247 Operand = I.getOperand(i);
1248 if (Operand->getType() != TheType) {
1249 PrintAllTypes = true; // We have differing types! Print them all!
1255 if (!PrintAllTypes) {
1260 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1262 writeOperand(I.getOperand(i), PrintAllTypes);
1266 printInfoComment(I);
1271 //===----------------------------------------------------------------------===//
1272 // External Interface declarations
1273 //===----------------------------------------------------------------------===//
1275 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1276 SlotMachine SlotTable(this);
1277 AssemblyWriter W(o, SlotTable, this, AAW);
1281 void GlobalVariable::print(std::ostream &o) const {
1282 SlotMachine SlotTable(getParent());
1283 AssemblyWriter W(o, SlotTable, getParent(), 0);
1287 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1288 SlotMachine SlotTable(getParent());
1289 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1294 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1295 WriteAsOperand(o, this, true, 0);
1298 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1299 SlotMachine SlotTable(getParent());
1300 AssemblyWriter W(o, SlotTable,
1301 getParent() ? getParent()->getParent() : 0, AAW);
1305 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1306 const Function *F = getParent() ? getParent()->getParent() : 0;
1307 SlotMachine SlotTable(F);
1308 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1313 void Constant::print(std::ostream &o) const {
1314 if (this == 0) { o << "<null> constant value\n"; return; }
1316 o << ' ' << getType()->getDescription() << ' ';
1318 std::map<const Type *, std::string> TypeTable;
1319 WriteConstantInt(o, this, TypeTable, 0);
1322 void Type::print(std::ostream &o) const {
1326 o << getDescription();
1329 void Argument::print(std::ostream &o) const {
1330 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1333 // Value::dump - allow easy printing of Values from the debugger.
1334 // Located here because so much of the needed functionality is here.
1335 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1337 // Type::dump - allow easy printing of Values from the debugger.
1338 // Located here because so much of the needed functionality is here.
1339 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1341 //===----------------------------------------------------------------------===//
1342 // SlotMachine Implementation
1343 //===----------------------------------------------------------------------===//
1346 #define SC_DEBUG(X) cerr << X
1351 // Module level constructor. Causes the contents of the Module (sans functions)
1352 // to be added to the slot table.
1353 SlotMachine::SlotMachine(const Module *M)
1354 : TheModule(M) ///< Saved for lazy initialization.
1356 , FunctionProcessed(false)
1360 // Function level constructor. Causes the contents of the Module and the one
1361 // function provided to be added to the slot table.
1362 SlotMachine::SlotMachine(const Function *F)
1363 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1364 , TheFunction(F) ///< Saved for lazy initialization
1365 , FunctionProcessed(false)
1369 inline void SlotMachine::initialize(void) {
1372 TheModule = 0; ///< Prevent re-processing next time we're called.
1374 if (TheFunction && !FunctionProcessed)
1378 // Iterate through all the global variables, functions, and global
1379 // variable initializers and create slots for them.
1380 void SlotMachine::processModule() {
1381 SC_DEBUG("begin processModule!\n");
1383 // Add all of the unnamed global variables to the value table.
1384 for (Module::const_global_iterator I = TheModule->global_begin(),
1385 E = TheModule->global_end(); I != E; ++I)
1389 // Add all the unnamed functions to the table.
1390 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1395 SC_DEBUG("end processModule!\n");
1399 // Process the arguments, basic blocks, and instructions of a function.
1400 void SlotMachine::processFunction() {
1401 SC_DEBUG("begin processFunction!\n");
1403 // Add all the function arguments with no names.
1404 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1405 AE = TheFunction->arg_end(); AI != AE; ++AI)
1407 getOrCreateSlot(AI);
1409 SC_DEBUG("Inserting Instructions:\n");
1411 // Add all of the basic blocks and instructions with no names.
1412 for (Function::const_iterator BB = TheFunction->begin(),
1413 E = TheFunction->end(); BB != E; ++BB) {
1415 getOrCreateSlot(BB);
1416 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1417 if (I->getType() != Type::VoidTy && !I->hasName())
1421 FunctionProcessed = true;
1423 SC_DEBUG("end processFunction!\n");
1426 /// Clean up after incorporating a function. This is the only way to get out of
1427 /// the function incorporation state that affects the
1428 /// getSlot/getOrCreateSlot lock. Function incorporation state is indicated
1429 /// by TheFunction != 0.
1430 void SlotMachine::purgeFunction() {
1431 SC_DEBUG("begin purgeFunction!\n");
1432 fMap.clear(); // Simply discard the function level map
1434 FunctionProcessed = false;
1435 SC_DEBUG("end purgeFunction!\n");
1438 /// Get the slot number for a value. This function will assert if you
1439 /// ask for a Value that hasn't previously been inserted with getOrCreateSlot.
1440 /// Types are forbidden because Type does not inherit from Value (any more).
1441 int SlotMachine::getSlot(const Value *V) {
1442 assert(V && "Can't get slot for null Value");
1443 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1444 "Can't insert a non-GlobalValue Constant into SlotMachine");
1446 // Check for uninitialized state and do lazy initialization
1449 // Get the type of the value
1450 const Type* VTy = V->getType();
1452 // Find the type plane in the module map
1453 TypedPlanes::const_iterator MI = mMap.find(VTy);
1456 // Lookup the type in the function map too
1457 TypedPlanes::const_iterator FI = fMap.find(VTy);
1458 // If there is a corresponding type plane in the function map
1459 if (FI != fMap.end()) {
1460 // Lookup the Value in the function map
1461 ValueMap::const_iterator FVI = FI->second.map.find(V);
1462 // If the value doesn't exist in the function map
1463 if (FVI == FI->second.map.end()) {
1464 // Look up the value in the module map.
1465 if (MI == mMap.end()) return -1;
1466 ValueMap::const_iterator MVI = MI->second.map.find(V);
1467 // If we didn't find it, it wasn't inserted
1468 if (MVI == MI->second.map.end()) return -1;
1469 assert(MVI != MI->second.map.end() && "Value not found");
1470 // We found it only at the module level
1473 // else the value exists in the function map
1475 // Return the slot number as the module's contribution to
1476 // the type plane plus the index in the function's contribution
1477 // to the type plane.
1478 if (MI != mMap.end())
1479 return MI->second.next_slot + FVI->second;
1486 // N.B. Can get here only if either !TheFunction or the function doesn't
1487 // have a corresponding type plane for the Value
1489 // Make sure the type plane exists
1490 if (MI == mMap.end()) return -1;
1491 // Lookup the value in the module's map
1492 ValueMap::const_iterator MVI = MI->second.map.find(V);
1493 // Make sure we found it.
1494 if (MVI == MI->second.map.end()) return -1;
1500 // Create a new slot, or return the existing slot if it is already
1501 // inserted. Note that the logic here parallels getSlot but instead
1502 // of asserting when the Value* isn't found, it inserts the value.
1503 unsigned SlotMachine::getOrCreateSlot(const Value *V) {
1504 const Type* VTy = V->getType();
1505 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1506 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1507 "Can't insert a non-GlobalValue Constant into SlotMachine");
1509 // Look up the type plane for the Value's type from the module map
1510 TypedPlanes::const_iterator MI = mMap.find(VTy);
1513 // Get the type plane for the Value's type from the function map
1514 TypedPlanes::const_iterator FI = fMap.find(VTy);
1515 // If there is a corresponding type plane in the function map
1516 if (FI != fMap.end()) {
1517 // Lookup the Value in the function map
1518 ValueMap::const_iterator FVI = FI->second.map.find(V);
1519 // If the value doesn't exist in the function map
1520 if (FVI == FI->second.map.end()) {
1521 // If there is no corresponding type plane in the module map
1522 if (MI == mMap.end())
1523 return insertValue(V);
1524 // Look up the value in the module map
1525 ValueMap::const_iterator MVI = MI->second.map.find(V);
1526 // If we didn't find it, it wasn't inserted
1527 if (MVI == MI->second.map.end())
1528 return insertValue(V);
1530 // We found it only at the module level
1533 // else the value exists in the function map
1535 if (MI == mMap.end())
1538 // Return the slot number as the module's contribution to
1539 // the type plane plus the index in the function's contribution
1540 // to the type plane.
1541 return MI->second.next_slot + FVI->second;
1544 // else there is not a corresponding type plane in the function map
1546 // If the type plane doesn't exists at the module level
1547 if (MI == mMap.end()) {
1548 return insertValue(V);
1549 // else type plane exists at the module level, examine it
1551 // Look up the value in the module's map
1552 ValueMap::const_iterator MVI = MI->second.map.find(V);
1553 // If we didn't find it there either
1554 if (MVI == MI->second.map.end())
1555 // Return the slot number as the module's contribution to
1556 // the type plane plus the index of the function map insertion.
1557 return MI->second.next_slot + insertValue(V);
1564 // N.B. Can only get here if TheFunction == 0
1566 // If the module map's type plane is not for the Value's type
1567 if (MI != mMap.end()) {
1568 // Lookup the value in the module's map
1569 ValueMap::const_iterator MVI = MI->second.map.find(V);
1570 if (MVI != MI->second.map.end())
1574 return insertValue(V);
1578 // Low level insert function. Minimal checking is done. This
1579 // function is just for the convenience of getOrCreateSlot (above).
1580 unsigned SlotMachine::insertValue(const Value *V) {
1581 assert(V && "Can't insert a null Value into SlotMachine!");
1582 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1583 "Can't insert a non-GlobalValue Constant into SlotMachine");
1584 assert(V->getType() != Type::VoidTy && !V->hasName());
1586 const Type *VTy = V->getType();
1587 unsigned DestSlot = 0;
1590 TypedPlanes::iterator I = fMap.find(VTy);
1591 if (I == fMap.end())
1592 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1593 DestSlot = I->second.map[V] = I->second.next_slot++;
1595 TypedPlanes::iterator I = mMap.find(VTy);
1596 if (I == mMap.end())
1597 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1598 DestSlot = I->second.map[V] = I->second.next_slot++;
1601 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1603 // G = Global, F = Function, o = other
1604 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 'o')));