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 ";
926 switch (F->getLinkage()) {
927 case GlobalValue::InternalLinkage: Out << "internal "; break;
928 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
929 case GlobalValue::WeakLinkage: Out << "weak "; break;
930 case GlobalValue::AppendingLinkage: Out << "appending "; break;
931 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
932 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
933 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
934 case GlobalValue::ExternalLinkage: break;
935 case GlobalValue::GhostLinkage:
936 cerr << "GhostLinkage not allowed in AsmWriter!\n";
941 // Print the calling convention.
942 switch (F->getCallingConv()) {
943 case CallingConv::C: break; // default
944 case CallingConv::CSRet: Out << "csretcc "; break;
945 case CallingConv::Fast: Out << "fastcc "; break;
946 case CallingConv::Cold: Out << "coldcc "; break;
947 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
948 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
949 default: Out << "cc" << F->getCallingConv() << " "; break;
952 printType(F->getReturnType()) << ' ';
953 if (!F->getName().empty())
954 Out << getLLVMName(F->getName());
958 Machine.incorporateFunction(F);
960 // Loop over the arguments, printing them...
961 const FunctionType *FT = F->getFunctionType();
963 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
967 // Finish printing arguments...
968 if (FT->isVarArg()) {
969 if (FT->getNumParams()) Out << ", ";
970 Out << "..."; // Output varargs portion of signature!
975 Out << " section \"" << F->getSection() << '"';
976 if (F->getAlignment())
977 Out << " align " << F->getAlignment();
979 if (F->isExternal()) {
984 // Output all of its basic blocks... for the function
985 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
991 Machine.purgeFunction();
994 /// printArgument - This member is called for every argument that is passed into
995 /// the function. Simply print it out
997 void AssemblyWriter::printArgument(const Argument *Arg) {
998 // Insert commas as we go... the first arg doesn't get a comma
999 if (Arg != Arg->getParent()->arg_begin()) Out << ", ";
1002 printType(Arg->getType());
1004 // Output name, if available...
1006 Out << ' ' << getLLVMName(Arg->getName());
1009 /// printBasicBlock - This member is called for each basic block in a method.
1011 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1012 if (BB->hasName()) { // Print out the label if it exists...
1013 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1014 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1015 Out << "\n; <label>:";
1016 int Slot = Machine.getSlot(BB);
1023 if (BB->getParent() == 0)
1024 Out << "\t\t; Error: Block without parent!";
1026 if (BB != &BB->getParent()->front()) { // Not the entry block?
1027 // Output predecessors for the block...
1029 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1032 Out << " No predecessors!";
1035 writeOperand(*PI, false);
1036 for (++PI; PI != PE; ++PI) {
1038 writeOperand(*PI, false);
1046 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1048 // Output all of the instructions in the basic block...
1049 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1050 printInstruction(*I);
1052 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1056 /// printInfoComment - Print a little comment after the instruction indicating
1057 /// which slot it occupies.
1059 void AssemblyWriter::printInfoComment(const Value &V) {
1060 if (V.getType() != Type::VoidTy) {
1062 printType(V.getType()) << '>';
1065 int SlotNum = Machine.getSlot(&V);
1069 Out << ':' << SlotNum; // Print out the def slot taken.
1071 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1075 // This member is called for each Instruction in a function..
1076 void AssemblyWriter::printInstruction(const Instruction &I) {
1077 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1081 // Print out name if it exists...
1083 Out << getLLVMName(I.getName()) << " = ";
1085 // If this is a volatile load or store, print out the volatile marker.
1086 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1087 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1089 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1090 // If this is a call, check if it's a tail call.
1094 // Print out the opcode...
1095 Out << I.getOpcodeName();
1097 // Print out the compare instruction predicates
1098 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1099 Out << " " << getPredicateText(FCI->getPredicate());
1100 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1101 Out << " " << getPredicateText(ICI->getPredicate());
1104 // Print out the type of the operands...
1105 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1107 // Special case conditional branches to swizzle the condition out to the front
1108 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1109 writeOperand(I.getOperand(2), true);
1111 writeOperand(Operand, true);
1113 writeOperand(I.getOperand(1), true);
1115 } else if (isa<SwitchInst>(I)) {
1116 // Special case switch statement to get formatting nice and correct...
1117 writeOperand(Operand , true); Out << ',';
1118 writeOperand(I.getOperand(1), true); Out << " [";
1120 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1122 writeOperand(I.getOperand(op ), true); Out << ',';
1123 writeOperand(I.getOperand(op+1), true);
1126 } else if (isa<PHINode>(I)) {
1128 printType(I.getType());
1131 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1132 if (op) Out << ", ";
1134 writeOperand(I.getOperand(op ), false); Out << ',';
1135 writeOperand(I.getOperand(op+1), false); Out << " ]";
1137 } else if (isa<ReturnInst>(I) && !Operand) {
1139 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1140 // Print the calling convention being used.
1141 switch (CI->getCallingConv()) {
1142 case CallingConv::C: break; // default
1143 case CallingConv::CSRet: Out << " csretcc"; break;
1144 case CallingConv::Fast: Out << " fastcc"; break;
1145 case CallingConv::Cold: Out << " coldcc"; break;
1146 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1147 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1148 default: Out << " cc" << CI->getCallingConv(); break;
1151 const PointerType *PTy = cast<PointerType>(Operand->getType());
1152 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1153 const Type *RetTy = FTy->getReturnType();
1155 // If possible, print out the short form of the call instruction. We can
1156 // only do this if the first argument is a pointer to a nonvararg function,
1157 // and if the return type is not a pointer to a function.
1159 if (!FTy->isVarArg() &&
1160 (!isa<PointerType>(RetTy) ||
1161 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1162 Out << ' '; printType(RetTy);
1163 writeOperand(Operand, false);
1165 writeOperand(Operand, true);
1168 if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true);
1169 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
1171 writeOperand(I.getOperand(op), true);
1175 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1176 const PointerType *PTy = cast<PointerType>(Operand->getType());
1177 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1178 const Type *RetTy = FTy->getReturnType();
1180 // Print the calling convention being used.
1181 switch (II->getCallingConv()) {
1182 case CallingConv::C: break; // default
1183 case CallingConv::CSRet: Out << " csretcc"; break;
1184 case CallingConv::Fast: Out << " fastcc"; break;
1185 case CallingConv::Cold: Out << " coldcc"; break;
1186 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1187 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1188 default: Out << " cc" << II->getCallingConv(); break;
1191 // If possible, print out the short form of the invoke instruction. We can
1192 // only do this if the first argument is a pointer to a nonvararg function,
1193 // and if the return type is not a pointer to a function.
1195 if (!FTy->isVarArg() &&
1196 (!isa<PointerType>(RetTy) ||
1197 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1198 Out << ' '; printType(RetTy);
1199 writeOperand(Operand, false);
1201 writeOperand(Operand, true);
1205 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1206 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1208 writeOperand(I.getOperand(op), true);
1211 Out << " )\n\t\t\tto";
1212 writeOperand(II->getNormalDest(), true);
1214 writeOperand(II->getUnwindDest(), true);
1216 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1218 printType(AI->getType()->getElementType());
1219 if (AI->isArrayAllocation()) {
1221 writeOperand(AI->getArraySize(), true);
1223 if (AI->getAlignment()) {
1224 Out << ", align " << AI->getAlignment();
1226 } else if (isa<CastInst>(I)) {
1227 if (Operand) writeOperand(Operand, true); // Work with broken code
1229 printType(I.getType());
1230 } else if (isa<VAArgInst>(I)) {
1231 if (Operand) writeOperand(Operand, true); // Work with broken code
1233 printType(I.getType());
1234 } else if (Operand) { // Print the normal way...
1236 // PrintAllTypes - Instructions who have operands of all the same type
1237 // omit the type from all but the first operand. If the instruction has
1238 // different type operands (for example br), then they are all printed.
1239 bool PrintAllTypes = false;
1240 const Type *TheType = Operand->getType();
1242 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1243 // types even if all operands are bools.
1244 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1245 isa<ShuffleVectorInst>(I)) {
1246 PrintAllTypes = true;
1248 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1249 Operand = I.getOperand(i);
1250 if (Operand->getType() != TheType) {
1251 PrintAllTypes = true; // We have differing types! Print them all!
1257 if (!PrintAllTypes) {
1262 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1264 writeOperand(I.getOperand(i), PrintAllTypes);
1268 printInfoComment(I);
1273 //===----------------------------------------------------------------------===//
1274 // External Interface declarations
1275 //===----------------------------------------------------------------------===//
1277 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1278 SlotMachine SlotTable(this);
1279 AssemblyWriter W(o, SlotTable, this, AAW);
1283 void GlobalVariable::print(std::ostream &o) const {
1284 SlotMachine SlotTable(getParent());
1285 AssemblyWriter W(o, SlotTable, getParent(), 0);
1289 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1290 SlotMachine SlotTable(getParent());
1291 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1296 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1297 WriteAsOperand(o, this, true, 0);
1300 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1301 SlotMachine SlotTable(getParent());
1302 AssemblyWriter W(o, SlotTable,
1303 getParent() ? getParent()->getParent() : 0, AAW);
1307 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1308 const Function *F = getParent() ? getParent()->getParent() : 0;
1309 SlotMachine SlotTable(F);
1310 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1315 void Constant::print(std::ostream &o) const {
1316 if (this == 0) { o << "<null> constant value\n"; return; }
1318 o << ' ' << getType()->getDescription() << ' ';
1320 std::map<const Type *, std::string> TypeTable;
1321 WriteConstantInt(o, this, TypeTable, 0);
1324 void Type::print(std::ostream &o) const {
1328 o << getDescription();
1331 void Argument::print(std::ostream &o) const {
1332 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1335 // Value::dump - allow easy printing of Values from the debugger.
1336 // Located here because so much of the needed functionality is here.
1337 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1339 // Type::dump - allow easy printing of Values from the debugger.
1340 // Located here because so much of the needed functionality is here.
1341 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1343 //===----------------------------------------------------------------------===//
1344 // SlotMachine Implementation
1345 //===----------------------------------------------------------------------===//
1348 #define SC_DEBUG(X) cerr << X
1353 // Module level constructor. Causes the contents of the Module (sans functions)
1354 // to be added to the slot table.
1355 SlotMachine::SlotMachine(const Module *M)
1356 : TheModule(M) ///< Saved for lazy initialization.
1358 , FunctionProcessed(false)
1362 // Function level constructor. Causes the contents of the Module and the one
1363 // function provided to be added to the slot table.
1364 SlotMachine::SlotMachine(const Function *F)
1365 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1366 , TheFunction(F) ///< Saved for lazy initialization
1367 , FunctionProcessed(false)
1371 inline void SlotMachine::initialize(void) {
1374 TheModule = 0; ///< Prevent re-processing next time we're called.
1376 if (TheFunction && !FunctionProcessed)
1380 // Iterate through all the global variables, functions, and global
1381 // variable initializers and create slots for them.
1382 void SlotMachine::processModule() {
1383 SC_DEBUG("begin processModule!\n");
1385 // Add all of the unnamed global variables to the value table.
1386 for (Module::const_global_iterator I = TheModule->global_begin(),
1387 E = TheModule->global_end(); I != E; ++I)
1391 // Add all the unnamed functions to the table.
1392 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1397 SC_DEBUG("end processModule!\n");
1401 // Process the arguments, basic blocks, and instructions of a function.
1402 void SlotMachine::processFunction() {
1403 SC_DEBUG("begin processFunction!\n");
1405 // Add all the function arguments with no names.
1406 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1407 AE = TheFunction->arg_end(); AI != AE; ++AI)
1409 getOrCreateSlot(AI);
1411 SC_DEBUG("Inserting Instructions:\n");
1413 // Add all of the basic blocks and instructions with no names.
1414 for (Function::const_iterator BB = TheFunction->begin(),
1415 E = TheFunction->end(); BB != E; ++BB) {
1417 getOrCreateSlot(BB);
1418 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1419 if (I->getType() != Type::VoidTy && !I->hasName())
1423 FunctionProcessed = true;
1425 SC_DEBUG("end processFunction!\n");
1428 /// Clean up after incorporating a function. This is the only way to get out of
1429 /// the function incorporation state that affects the
1430 /// getSlot/getOrCreateSlot lock. Function incorporation state is indicated
1431 /// by TheFunction != 0.
1432 void SlotMachine::purgeFunction() {
1433 SC_DEBUG("begin purgeFunction!\n");
1434 fMap.clear(); // Simply discard the function level map
1436 FunctionProcessed = false;
1437 SC_DEBUG("end purgeFunction!\n");
1440 /// Get the slot number for a value. This function will assert if you
1441 /// ask for a Value that hasn't previously been inserted with getOrCreateSlot.
1442 /// Types are forbidden because Type does not inherit from Value (any more).
1443 int SlotMachine::getSlot(const Value *V) {
1444 assert(V && "Can't get slot for null Value");
1445 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1446 "Can't insert a non-GlobalValue Constant into SlotMachine");
1448 // Check for uninitialized state and do lazy initialization
1451 // Get the type of the value
1452 const Type* VTy = V->getType();
1454 // Find the type plane in the module map
1455 TypedPlanes::const_iterator MI = mMap.find(VTy);
1458 // Lookup the type in the function map too
1459 TypedPlanes::const_iterator FI = fMap.find(VTy);
1460 // If there is a corresponding type plane in the function map
1461 if (FI != fMap.end()) {
1462 // Lookup the Value in the function map
1463 ValueMap::const_iterator FVI = FI->second.map.find(V);
1464 // If the value doesn't exist in the function map
1465 if (FVI == FI->second.map.end()) {
1466 // Look up the value in the module map.
1467 if (MI == mMap.end()) return -1;
1468 ValueMap::const_iterator MVI = MI->second.map.find(V);
1469 // If we didn't find it, it wasn't inserted
1470 if (MVI == MI->second.map.end()) return -1;
1471 assert(MVI != MI->second.map.end() && "Value not found");
1472 // We found it only at the module level
1475 // else the value exists in the function map
1477 // Return the slot number as the module's contribution to
1478 // the type plane plus the index in the function's contribution
1479 // to the type plane.
1480 if (MI != mMap.end())
1481 return MI->second.next_slot + FVI->second;
1488 // N.B. Can get here only if either !TheFunction or the function doesn't
1489 // have a corresponding type plane for the Value
1491 // Make sure the type plane exists
1492 if (MI == mMap.end()) return -1;
1493 // Lookup the value in the module's map
1494 ValueMap::const_iterator MVI = MI->second.map.find(V);
1495 // Make sure we found it.
1496 if (MVI == MI->second.map.end()) return -1;
1502 // Create a new slot, or return the existing slot if it is already
1503 // inserted. Note that the logic here parallels getSlot but instead
1504 // of asserting when the Value* isn't found, it inserts the value.
1505 unsigned SlotMachine::getOrCreateSlot(const Value *V) {
1506 const Type* VTy = V->getType();
1507 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1508 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1509 "Can't insert a non-GlobalValue Constant into SlotMachine");
1511 // Look up the type plane for the Value's type from the module map
1512 TypedPlanes::const_iterator MI = mMap.find(VTy);
1515 // Get the type plane for the Value's type from the function map
1516 TypedPlanes::const_iterator FI = fMap.find(VTy);
1517 // If there is a corresponding type plane in the function map
1518 if (FI != fMap.end()) {
1519 // Lookup the Value in the function map
1520 ValueMap::const_iterator FVI = FI->second.map.find(V);
1521 // If the value doesn't exist in the function map
1522 if (FVI == FI->second.map.end()) {
1523 // If there is no corresponding type plane in the module map
1524 if (MI == mMap.end())
1525 return insertValue(V);
1526 // Look up the value in the module map
1527 ValueMap::const_iterator MVI = MI->second.map.find(V);
1528 // If we didn't find it, it wasn't inserted
1529 if (MVI == MI->second.map.end())
1530 return insertValue(V);
1532 // We found it only at the module level
1535 // else the value exists in the function map
1537 if (MI == mMap.end())
1540 // Return the slot number as the module's contribution to
1541 // the type plane plus the index in the function's contribution
1542 // to the type plane.
1543 return MI->second.next_slot + FVI->second;
1546 // else there is not a corresponding type plane in the function map
1548 // If the type plane doesn't exists at the module level
1549 if (MI == mMap.end()) {
1550 return insertValue(V);
1551 // else type plane exists at the module level, examine it
1553 // Look up the value in the module's map
1554 ValueMap::const_iterator MVI = MI->second.map.find(V);
1555 // If we didn't find it there either
1556 if (MVI == MI->second.map.end())
1557 // Return the slot number as the module's contribution to
1558 // the type plane plus the index of the function map insertion.
1559 return MI->second.next_slot + insertValue(V);
1566 // N.B. Can only get here if TheFunction == 0
1568 // If the module map's type plane is not for the Value's type
1569 if (MI != mMap.end()) {
1570 // Lookup the value in the module's map
1571 ValueMap::const_iterator MVI = MI->second.map.find(V);
1572 if (MVI != MI->second.map.end())
1576 return insertValue(V);
1580 // Low level insert function. Minimal checking is done. This
1581 // function is just for the convenience of getOrCreateSlot (above).
1582 unsigned SlotMachine::insertValue(const Value *V) {
1583 assert(V && "Can't insert a null Value into SlotMachine!");
1584 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1585 "Can't insert a non-GlobalValue Constant into SlotMachine");
1586 assert(V->getType() != Type::VoidTy && !V->hasName());
1588 const Type *VTy = V->getType();
1589 unsigned DestSlot = 0;
1592 TypedPlanes::iterator I = fMap.find(VTy);
1593 if (I == fMap.end())
1594 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1595 DestSlot = I->second.map[V] = I->second.next_slot++;
1597 TypedPlanes::iterator I = mMap.find(VTy);
1598 if (I == mMap.end())
1599 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1600 DestSlot = I->second.map[V] = I->second.next_slot++;
1603 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1605 // G = Global, F = Function, o = other
1606 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 'o')));