1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Assembly/CachedWriter.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/Assembly/AsmAnnotationWriter.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instruction.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Module.h"
28 #include "llvm/SymbolTable.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Streams.h"
39 // Make virtual table appear in this compilation unit.
40 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
42 /// This class provides computation of slot numbers for LLVM Assembly writing.
43 /// @brief LLVM Assembly Writing Slot Computation.
50 /// @brief A mapping of Values to slot numbers
51 typedef std::map<const Value*, unsigned> ValueMap;
53 /// @brief A plane with next slot number and ValueMap
55 unsigned next_slot; ///< The next slot number to use
56 ValueMap map; ///< The map of Value* -> unsigned
57 ValuePlane() { next_slot = 0; } ///< Make sure we start at 0
60 /// @brief The map of planes by Type
61 typedef std::map<const Type*, ValuePlane> TypedPlanes;
64 /// @name Constructors
67 /// @brief Construct from a module
68 SlotMachine(const Module *M);
70 /// @brief Construct from a function, starting out in incorp state.
71 SlotMachine(const Function *F);
77 /// Return the slot number of the specified value in it's type
78 /// plane. Its an error to ask for something not in the SlotMachine.
79 /// Its an error to ask for a Type*
80 int getSlot(const Value *V);
86 /// If you'd like to deal with a function instead of just a module, use
87 /// this method to get its data into the SlotMachine.
88 void incorporateFunction(const Function *F) {
90 FunctionProcessed = false;
93 /// After calling incorporateFunction, use this method to remove the
94 /// most recently incorporated function from the SlotMachine. This
95 /// will reset the state of the machine back to just the module contents.
99 /// @name Implementation Details
102 /// This function does the actual initialization.
103 inline void initialize();
105 /// Values can be crammed into here at will. If they haven't
106 /// been inserted already, they get inserted, otherwise they are ignored.
107 /// Either way, the slot number for the Value* is returned.
108 unsigned getOrCreateSlot(const Value *V);
110 /// Insert a value into the value table. Return the slot number
111 /// that it now occupies. BadThings(TM) will happen if you insert a
112 /// Value that's already been inserted.
113 unsigned insertValue(const Value *V);
115 /// Add all of the module level global variables (and their initializers)
116 /// and function declarations, but not the contents of those functions.
117 void processModule();
119 /// Add all of the functions arguments, basic blocks, and instructions
120 void processFunction();
122 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
123 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
130 /// @brief The module for which we are holding slot numbers
131 const Module* TheModule;
133 /// @brief The function for which we are holding slot numbers
134 const Function* TheFunction;
135 bool FunctionProcessed;
137 /// @brief The TypePlanes map for the module level data
140 /// @brief The TypePlanes map for the function level data
147 } // end namespace llvm
149 static RegisterPass<PrintModulePass>
150 X("printm", "Print module to stderr");
151 static RegisterPass<PrintFunctionPass>
152 Y("print","Print function to stderr");
154 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
155 std::map<const Type *, std::string> &TypeTable,
156 SlotMachine *Machine);
158 static const Module *getModuleFromVal(const Value *V) {
159 if (const Argument *MA = dyn_cast<Argument>(V))
160 return MA->getParent() ? MA->getParent()->getParent() : 0;
161 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
162 return BB->getParent() ? BB->getParent()->getParent() : 0;
163 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
164 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
165 return M ? M->getParent() : 0;
166 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
167 return GV->getParent();
171 static SlotMachine *createSlotMachine(const Value *V) {
172 if (const Argument *FA = dyn_cast<Argument>(V)) {
173 return new SlotMachine(FA->getParent());
174 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
175 return new SlotMachine(I->getParent()->getParent());
176 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
177 return new SlotMachine(BB->getParent());
178 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
179 return new SlotMachine(GV->getParent());
180 } else if (const Function *Func = dyn_cast<Function>(V)) {
181 return new SlotMachine(Func);
186 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
187 // prefixed with % (if the string only contains simple characters) or is
188 // surrounded with ""'s (if it has special chars in it).
189 static std::string getLLVMName(const std::string &Name,
190 bool prefixName = true) {
191 assert(!Name.empty() && "Cannot get empty name!");
193 // First character cannot start with a number...
194 if (Name[0] >= '0' && Name[0] <= '9')
195 return "\"" + Name + "\"";
197 // Scan to see if we have any characters that are not on the "white list"
198 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
200 assert(C != '"' && "Illegal character in LLVM value name!");
201 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
202 C != '-' && C != '.' && C != '_')
203 return "\"" + Name + "\"";
206 // If we get here, then the identifier is legal to use as a "VarID".
214 /// fillTypeNameTable - If the module has a symbol table, take all global types
215 /// and stuff their names into the TypeNames map.
217 static void fillTypeNameTable(const Module *M,
218 std::map<const Type *, std::string> &TypeNames) {
220 const SymbolTable &ST = M->getSymbolTable();
221 SymbolTable::type_const_iterator TI = ST.type_begin();
222 for (; TI != ST.type_end(); ++TI) {
223 // As a heuristic, don't insert pointer to primitive types, because
224 // they are used too often to have a single useful name.
226 const Type *Ty = cast<Type>(TI->second);
227 if (!isa<PointerType>(Ty) ||
228 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
229 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
230 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
236 static void calcTypeName(const Type *Ty,
237 std::vector<const Type *> &TypeStack,
238 std::map<const Type *, std::string> &TypeNames,
239 std::string & Result){
240 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
241 Result += Ty->getDescription(); // Base case
245 // Check to see if the type is named.
246 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
247 if (I != TypeNames.end()) {
252 if (isa<OpaqueType>(Ty)) {
257 // Check to see if the Type is already on the stack...
258 unsigned Slot = 0, CurSize = TypeStack.size();
259 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
261 // This is another base case for the recursion. In this case, we know
262 // that we have looped back to a type that we have previously visited.
263 // Generate the appropriate upreference to handle this.
264 if (Slot < CurSize) {
265 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
269 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
271 switch (Ty->getTypeID()) {
272 case Type::FunctionTyID: {
273 const FunctionType *FTy = cast<FunctionType>(Ty);
274 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
276 for (FunctionType::param_iterator I = FTy->param_begin(),
277 E = FTy->param_end(); I != E; ++I) {
278 if (I != FTy->param_begin())
280 calcTypeName(*I, TypeStack, TypeNames, Result);
282 if (FTy->isVarArg()) {
283 if (FTy->getNumParams()) Result += ", ";
289 case Type::StructTyID: {
290 const StructType *STy = cast<StructType>(Ty);
292 for (StructType::element_iterator I = STy->element_begin(),
293 E = STy->element_end(); I != E; ++I) {
294 if (I != STy->element_begin())
296 calcTypeName(*I, TypeStack, TypeNames, Result);
301 case Type::PointerTyID:
302 calcTypeName(cast<PointerType>(Ty)->getElementType(),
303 TypeStack, TypeNames, Result);
306 case Type::ArrayTyID: {
307 const ArrayType *ATy = cast<ArrayType>(Ty);
308 Result += "[" + utostr(ATy->getNumElements()) + " x ";
309 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
313 case Type::PackedTyID: {
314 const PackedType *PTy = cast<PackedType>(Ty);
315 Result += "<" + utostr(PTy->getNumElements()) + " x ";
316 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
320 case Type::OpaqueTyID:
324 Result += "<unrecognized-type>";
327 TypeStack.pop_back(); // Remove self from stack...
332 /// printTypeInt - The internal guts of printing out a type that has a
333 /// potentially named portion.
335 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
336 std::map<const Type *, std::string> &TypeNames) {
337 // Primitive types always print out their description, regardless of whether
338 // they have been named or not.
340 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
341 return Out << Ty->getDescription();
343 // Check to see if the type is named.
344 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
345 if (I != TypeNames.end()) return Out << I->second;
347 // Otherwise we have a type that has not been named but is a derived type.
348 // Carefully recurse the type hierarchy to print out any contained symbolic
351 std::vector<const Type *> TypeStack;
352 std::string TypeName;
353 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
354 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
355 return (Out << TypeName);
359 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
360 /// type, iff there is an entry in the modules symbol table for the specified
361 /// type or one of it's component types. This is slower than a simple x << Type
363 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
367 // If they want us to print out a type, attempt to make it symbolic if there
368 // is a symbol table in the module...
370 std::map<const Type *, std::string> TypeNames;
371 fillTypeNameTable(M, TypeNames);
373 return printTypeInt(Out, Ty, TypeNames);
375 return Out << Ty->getDescription();
379 // PrintEscapedString - Print each character of the specified string, escaping
380 // it if it is not printable or if it is an escape char.
381 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
382 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
383 unsigned char C = Str[i];
384 if (isprint(C) && C != '"' && C != '\\') {
388 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
389 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
394 static const char * getPredicateText(unsigned predicate) {
395 const char * pred = "unknown";
397 case FCmpInst::FCMP_FALSE: pred = "false"; break;
398 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
399 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
400 case FCmpInst::FCMP_OGE: pred = "oge"; break;
401 case FCmpInst::FCMP_OLT: pred = "olt"; break;
402 case FCmpInst::FCMP_OLE: pred = "ole"; break;
403 case FCmpInst::FCMP_ONE: pred = "one"; break;
404 case FCmpInst::FCMP_ORD: pred = "ord"; break;
405 case FCmpInst::FCMP_UNO: pred = "uno"; break;
406 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
407 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
408 case FCmpInst::FCMP_UGE: pred = "uge"; break;
409 case FCmpInst::FCMP_ULT: pred = "ult"; break;
410 case FCmpInst::FCMP_ULE: pred = "ule"; break;
411 case FCmpInst::FCMP_UNE: pred = "une"; break;
412 case FCmpInst::FCMP_TRUE: pred = "true"; break;
413 case ICmpInst::ICMP_EQ: pred = "eq"; break;
414 case ICmpInst::ICMP_NE: pred = "ne"; break;
415 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
416 case ICmpInst::ICMP_SGE: pred = "sge"; break;
417 case ICmpInst::ICMP_SLT: pred = "slt"; break;
418 case ICmpInst::ICMP_SLE: pred = "sle"; break;
419 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
420 case ICmpInst::ICMP_UGE: pred = "uge"; break;
421 case ICmpInst::ICMP_ULT: pred = "ult"; break;
422 case ICmpInst::ICMP_ULE: pred = "ule"; break;
427 /// @brief Internal constant writer.
428 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
429 std::map<const Type *, std::string> &TypeTable,
430 SlotMachine *Machine) {
431 const int IndentSize = 4;
432 static std::string Indent = "\n";
433 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
434 Out << (CB->getValue() ? "true" : "false");
435 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
436 if (CI->getType()->isSigned())
437 Out << CI->getSExtValue();
439 Out << CI->getZExtValue();
440 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
441 // We would like to output the FP constant value in exponential notation,
442 // but we cannot do this if doing so will lose precision. Check here to
443 // make sure that we only output it in exponential format if we can parse
444 // the value back and get the same value.
446 std::string StrVal = ftostr(CFP->getValue());
448 // Check to make sure that the stringized number is not some string like
449 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
450 // the string matches the "[-+]?[0-9]" regex.
452 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
453 ((StrVal[0] == '-' || StrVal[0] == '+') &&
454 (StrVal[1] >= '0' && StrVal[1] <= '9')))
455 // Reparse stringized version!
456 if (atof(StrVal.c_str()) == CFP->getValue()) {
461 // Otherwise we could not reparse it to exactly the same value, so we must
462 // output the string in hexadecimal format!
463 assert(sizeof(double) == sizeof(uint64_t) &&
464 "assuming that double is 64 bits!");
465 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
467 } else if (isa<ConstantAggregateZero>(CV)) {
468 Out << "zeroinitializer";
469 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
470 // As a special case, print the array as a string if it is an array of
471 // ubytes or an array of sbytes with positive values.
473 const Type *ETy = CA->getType()->getElementType();
474 if (CA->isString()) {
476 PrintEscapedString(CA->getAsString(), Out);
479 } else { // Cannot output in string format...
481 if (CA->getNumOperands()) {
483 printTypeInt(Out, ETy, TypeTable);
484 WriteAsOperandInternal(Out, CA->getOperand(0),
486 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
488 printTypeInt(Out, ETy, TypeTable);
489 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
494 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
496 unsigned N = CS->getNumOperands();
499 Indent += std::string(IndentSize, ' ');
504 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
506 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
508 for (unsigned i = 1; i < N; i++) {
510 if (N > 2) Out << Indent;
511 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
513 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
515 if (N > 2) Indent.resize(Indent.size() - IndentSize);
519 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
520 const Type *ETy = CP->getType()->getElementType();
521 assert(CP->getNumOperands() > 0 &&
522 "Number of operands for a PackedConst must be > 0");
525 printTypeInt(Out, ETy, TypeTable);
526 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
527 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
529 printTypeInt(Out, ETy, TypeTable);
530 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
533 } else if (isa<ConstantPointerNull>(CV)) {
536 } else if (isa<UndefValue>(CV)) {
539 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
540 Out << CE->getOpcodeName();
542 Out << " " << getPredicateText(CE->getPredicate());
545 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
546 printTypeInt(Out, (*OI)->getType(), TypeTable);
547 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
548 if (OI+1 != CE->op_end())
554 printTypeInt(Out, CE->getType(), TypeTable);
560 Out << "<placeholder or erroneous Constant>";
565 /// WriteAsOperand - Write the name of the specified value out to the specified
566 /// ostream. This can be useful when you just want to print int %reg126, not
567 /// the whole instruction that generated it.
569 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
570 std::map<const Type*, std::string> &TypeTable,
571 SlotMachine *Machine) {
574 Out << getLLVMName(V->getName());
576 const Constant *CV = dyn_cast<Constant>(V);
577 if (CV && !isa<GlobalValue>(CV)) {
578 WriteConstantInt(Out, CV, TypeTable, Machine);
579 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
581 if (IA->hasSideEffects())
582 Out << "sideeffect ";
584 PrintEscapedString(IA->getAsmString(), Out);
586 PrintEscapedString(IA->getConstraintString(), Out);
591 Slot = Machine->getSlot(V);
593 Machine = createSlotMachine(V);
595 Slot = Machine->getSlot(V);
608 /// WriteAsOperand - Write the name of the specified value out to the specified
609 /// ostream. This can be useful when you just want to print int %reg126, not
610 /// the whole instruction that generated it.
612 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
613 bool PrintType, const Module *Context) {
614 std::map<const Type *, std::string> TypeNames;
615 if (Context == 0) Context = getModuleFromVal(V);
618 fillTypeNameTable(Context, TypeNames);
621 printTypeInt(Out, V->getType(), TypeNames);
623 WriteAsOperandInternal(Out, V, TypeNames, 0);
630 class AssemblyWriter {
632 SlotMachine &Machine;
633 const Module *TheModule;
634 std::map<const Type *, std::string> TypeNames;
635 AssemblyAnnotationWriter *AnnotationWriter;
637 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
638 AssemblyAnnotationWriter *AAW)
639 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
641 // If the module has a symbol table, take all global types and stuff their
642 // names into the TypeNames map.
644 fillTypeNameTable(M, TypeNames);
647 inline void write(const Module *M) { printModule(M); }
648 inline void write(const GlobalVariable *G) { printGlobal(G); }
649 inline void write(const Function *F) { printFunction(F); }
650 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
651 inline void write(const Instruction *I) { printInstruction(*I); }
652 inline void write(const Constant *CPV) { printConstant(CPV); }
653 inline void write(const Type *Ty) { printType(Ty); }
655 void writeOperand(const Value *Op, bool PrintType);
657 const Module* getModule() { return TheModule; }
660 void printModule(const Module *M);
661 void printSymbolTable(const SymbolTable &ST);
662 void printConstant(const Constant *CPV);
663 void printGlobal(const GlobalVariable *GV);
664 void printFunction(const Function *F);
665 void printArgument(const Argument *FA);
666 void printBasicBlock(const BasicBlock *BB);
667 void printInstruction(const Instruction &I);
669 // printType - Go to extreme measures to attempt to print out a short,
670 // symbolic version of a type name.
672 std::ostream &printType(const Type *Ty) {
673 return printTypeInt(Out, Ty, TypeNames);
676 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
677 // without considering any symbolic types that we may have equal to it.
679 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
681 // printInfoComment - Print a little comment after the instruction indicating
682 // which slot it occupies.
683 void printInfoComment(const Value &V);
685 } // end of llvm namespace
687 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
688 /// without considering any symbolic types that we may have equal to it.
690 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
691 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
692 printType(FTy->getReturnType()) << " (";
693 for (FunctionType::param_iterator I = FTy->param_begin(),
694 E = FTy->param_end(); I != E; ++I) {
695 if (I != FTy->param_begin())
699 if (FTy->isVarArg()) {
700 if (FTy->getNumParams()) Out << ", ";
704 } 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())
713 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
714 printType(PTy->getElementType()) << '*';
715 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
716 Out << '[' << ATy->getNumElements() << " x ";
717 printType(ATy->getElementType()) << ']';
718 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
719 Out << '<' << PTy->getNumElements() << " x ";
720 printType(PTy->getElementType()) << '>';
722 else if (isa<OpaqueType>(Ty)) {
725 if (!Ty->isPrimitiveType())
726 Out << "<unknown derived type>";
733 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
735 Out << "<null operand!>";
737 if (PrintType) { Out << ' '; printType(Operand->getType()); }
738 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
743 void AssemblyWriter::printModule(const Module *M) {
744 if (!M->getModuleIdentifier().empty() &&
745 // Don't print the ID if it will start a new line (which would
746 // require a comment char before it).
747 M->getModuleIdentifier().find('\n') == std::string::npos)
748 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
750 if (!M->getDataLayout().empty())
751 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
753 switch (M->getEndianness()) {
754 case Module::LittleEndian: Out << "target endian = little\n"; break;
755 case Module::BigEndian: Out << "target endian = big\n"; break;
756 case Module::AnyEndianness: break;
758 switch (M->getPointerSize()) {
759 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
760 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
761 case Module::AnyPointerSize: break;
763 if (!M->getTargetTriple().empty())
764 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
766 if (!M->getModuleInlineAsm().empty()) {
767 // Split the string into lines, to make it easier to read the .ll file.
768 std::string Asm = M->getModuleInlineAsm();
770 size_t NewLine = Asm.find_first_of('\n', CurPos);
771 while (NewLine != std::string::npos) {
772 // We found a newline, print the portion of the asm string from the
773 // last newline up to this newline.
774 Out << "module asm \"";
775 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
779 NewLine = Asm.find_first_of('\n', CurPos);
781 Out << "module asm \"";
782 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
786 // Loop over the dependent libraries and emit them.
787 Module::lib_iterator LI = M->lib_begin();
788 Module::lib_iterator LE = M->lib_end();
790 Out << "deplibs = [ ";
792 Out << '"' << *LI << '"';
800 // Loop over the symbol table, emitting all named constants.
801 printSymbolTable(M->getSymbolTable());
803 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
807 Out << "\nimplementation ; Functions:\n";
809 // Output all of the functions.
810 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
814 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
815 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
817 if (!GV->hasInitializer())
818 switch (GV->getLinkage()) {
819 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
820 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
821 default: Out << "external "; break;
824 switch (GV->getLinkage()) {
825 case GlobalValue::InternalLinkage: Out << "internal "; break;
826 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
827 case GlobalValue::WeakLinkage: Out << "weak "; break;
828 case GlobalValue::AppendingLinkage: Out << "appending "; break;
829 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
830 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
831 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
832 case GlobalValue::ExternalLinkage: break;
833 case GlobalValue::GhostLinkage:
834 llvm_cerr << "GhostLinkage not allowed in AsmWriter!\n";
838 Out << (GV->isConstant() ? "constant " : "global ");
839 printType(GV->getType()->getElementType());
841 if (GV->hasInitializer()) {
842 Constant* C = cast<Constant>(GV->getInitializer());
843 assert(C && "GlobalVar initializer isn't constant?");
844 writeOperand(GV->getInitializer(), false);
847 if (GV->hasSection())
848 Out << ", section \"" << GV->getSection() << '"';
849 if (GV->getAlignment())
850 Out << ", align " << GV->getAlignment();
852 printInfoComment(*GV);
857 // printSymbolTable - Run through symbol table looking for constants
858 // and types. Emit their declarations.
859 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
862 for (SymbolTable::type_const_iterator TI = ST.type_begin();
863 TI != ST.type_end(); ++TI) {
864 Out << "\t" << getLLVMName(TI->first) << " = type ";
866 // Make sure we print out at least one level of the type structure, so
867 // that we do not get %FILE = type %FILE
869 printTypeAtLeastOneLevel(TI->second) << "\n";
872 // Print the constants, in type plane order.
873 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
874 PI != ST.plane_end(); ++PI) {
875 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
876 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
878 for (; VI != VE; ++VI) {
879 const Value* V = VI->second;
880 const Constant *CPV = dyn_cast<Constant>(V) ;
881 if (CPV && !isa<GlobalValue>(V)) {
889 /// printConstant - Print out a constant pool entry...
891 void AssemblyWriter::printConstant(const Constant *CPV) {
892 // Don't print out unnamed constants, they will be inlined
893 if (!CPV->hasName()) return;
896 Out << "\t" << getLLVMName(CPV->getName()) << " =";
898 // Write the value out now.
899 writeOperand(CPV, true);
901 printInfoComment(*CPV);
905 /// printFunction - Print all aspects of a function.
907 void AssemblyWriter::printFunction(const Function *F) {
908 // Print out the return type and name...
911 // Ensure that no local symbols conflict with global symbols.
912 const_cast<Function*>(F)->renameLocalSymbols();
914 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
917 switch (F->getLinkage()) {
918 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
919 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
920 default: Out << "declare ";
923 switch (F->getLinkage()) {
924 case GlobalValue::InternalLinkage: Out << "internal "; break;
925 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
926 case GlobalValue::WeakLinkage: Out << "weak "; break;
927 case GlobalValue::AppendingLinkage: Out << "appending "; break;
928 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
929 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
930 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
931 case GlobalValue::ExternalLinkage: break;
932 case GlobalValue::GhostLinkage:
933 llvm_cerr << "GhostLinkage not allowed in AsmWriter!\n";
937 // Print the calling convention.
938 switch (F->getCallingConv()) {
939 case CallingConv::C: break; // default
940 case CallingConv::CSRet: Out << "csretcc "; break;
941 case CallingConv::Fast: Out << "fastcc "; break;
942 case CallingConv::Cold: Out << "coldcc "; break;
943 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
944 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
945 default: Out << "cc" << F->getCallingConv() << " "; break;
948 printType(F->getReturnType()) << ' ';
949 if (!F->getName().empty())
950 Out << getLLVMName(F->getName());
954 Machine.incorporateFunction(F);
956 // Loop over the arguments, printing them...
957 const FunctionType *FT = F->getFunctionType();
959 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
963 // Finish printing arguments...
964 if (FT->isVarArg()) {
965 if (FT->getNumParams()) Out << ", ";
966 Out << "..."; // Output varargs portion of signature!
971 Out << " section \"" << F->getSection() << '"';
972 if (F->getAlignment())
973 Out << " align " << F->getAlignment();
975 if (F->isExternal()) {
980 // Output all of its basic blocks... for the function
981 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
987 Machine.purgeFunction();
990 /// printArgument - This member is called for every argument that is passed into
991 /// the function. Simply print it out
993 void AssemblyWriter::printArgument(const Argument *Arg) {
994 // Insert commas as we go... the first arg doesn't get a comma
995 if (Arg != Arg->getParent()->arg_begin()) Out << ", ";
998 printType(Arg->getType());
1000 // Output name, if available...
1002 Out << ' ' << getLLVMName(Arg->getName());
1005 /// printBasicBlock - This member is called for each basic block in a method.
1007 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1008 if (BB->hasName()) { // Print out the label if it exists...
1009 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1010 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1011 Out << "\n; <label>:";
1012 int Slot = Machine.getSlot(BB);
1019 if (BB->getParent() == 0)
1020 Out << "\t\t; Error: Block without parent!";
1022 if (BB != &BB->getParent()->front()) { // Not the entry block?
1023 // Output predecessors for the block...
1025 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1028 Out << " No predecessors!";
1031 writeOperand(*PI, false);
1032 for (++PI; PI != PE; ++PI) {
1034 writeOperand(*PI, false);
1042 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1044 // Output all of the instructions in the basic block...
1045 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1046 printInstruction(*I);
1048 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1052 /// printInfoComment - Print a little comment after the instruction indicating
1053 /// which slot it occupies.
1055 void AssemblyWriter::printInfoComment(const Value &V) {
1056 if (V.getType() != Type::VoidTy) {
1058 printType(V.getType()) << '>';
1061 int SlotNum = Machine.getSlot(&V);
1065 Out << ':' << SlotNum; // Print out the def slot taken.
1067 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1071 // This member is called for each Instruction in a function..
1072 void AssemblyWriter::printInstruction(const Instruction &I) {
1073 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1077 // Print out name if it exists...
1079 Out << getLLVMName(I.getName()) << " = ";
1081 // If this is a volatile load or store, print out the volatile marker.
1082 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1083 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1085 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1086 // If this is a call, check if it's a tail call.
1090 // Print out the opcode...
1091 Out << I.getOpcodeName();
1093 // Print out the compare instruction predicates
1094 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1095 Out << " " << getPredicateText(FCI->getPredicate());
1096 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1097 Out << " " << getPredicateText(ICI->getPredicate());
1100 // Print out the type of the operands...
1101 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1103 // Special case conditional branches to swizzle the condition out to the front
1104 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1105 writeOperand(I.getOperand(2), true);
1107 writeOperand(Operand, true);
1109 writeOperand(I.getOperand(1), true);
1111 } else if (isa<SwitchInst>(I)) {
1112 // Special case switch statement to get formatting nice and correct...
1113 writeOperand(Operand , true); Out << ',';
1114 writeOperand(I.getOperand(1), true); Out << " [";
1116 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1118 writeOperand(I.getOperand(op ), true); Out << ',';
1119 writeOperand(I.getOperand(op+1), true);
1122 } else if (isa<PHINode>(I)) {
1124 printType(I.getType());
1127 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1128 if (op) Out << ", ";
1130 writeOperand(I.getOperand(op ), false); Out << ',';
1131 writeOperand(I.getOperand(op+1), false); Out << " ]";
1133 } else if (isa<ReturnInst>(I) && !Operand) {
1135 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1136 // Print the calling convention being used.
1137 switch (CI->getCallingConv()) {
1138 case CallingConv::C: break; // default
1139 case CallingConv::CSRet: Out << " csretcc"; break;
1140 case CallingConv::Fast: Out << " fastcc"; break;
1141 case CallingConv::Cold: Out << " coldcc"; break;
1142 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1143 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1144 default: Out << " cc" << CI->getCallingConv(); break;
1147 const PointerType *PTy = cast<PointerType>(Operand->getType());
1148 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1149 const Type *RetTy = FTy->getReturnType();
1151 // If possible, print out the short form of the call instruction. We can
1152 // only do this if the first argument is a pointer to a nonvararg function,
1153 // and if the return type is not a pointer to a function.
1155 if (!FTy->isVarArg() &&
1156 (!isa<PointerType>(RetTy) ||
1157 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1158 Out << ' '; printType(RetTy);
1159 writeOperand(Operand, false);
1161 writeOperand(Operand, true);
1164 if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true);
1165 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
1167 writeOperand(I.getOperand(op), true);
1171 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1172 const PointerType *PTy = cast<PointerType>(Operand->getType());
1173 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1174 const Type *RetTy = FTy->getReturnType();
1176 // Print the calling convention being used.
1177 switch (II->getCallingConv()) {
1178 case CallingConv::C: break; // default
1179 case CallingConv::CSRet: Out << " csretcc"; break;
1180 case CallingConv::Fast: Out << " fastcc"; break;
1181 case CallingConv::Cold: Out << " coldcc"; break;
1182 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1183 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1184 default: Out << " cc" << II->getCallingConv(); break;
1187 // If possible, print out the short form of the invoke instruction. We can
1188 // only do this if the first argument is a pointer to a nonvararg function,
1189 // and if the return type is not a pointer to a function.
1191 if (!FTy->isVarArg() &&
1192 (!isa<PointerType>(RetTy) ||
1193 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1194 Out << ' '; printType(RetTy);
1195 writeOperand(Operand, false);
1197 writeOperand(Operand, true);
1201 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1202 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1204 writeOperand(I.getOperand(op), true);
1207 Out << " )\n\t\t\tto";
1208 writeOperand(II->getNormalDest(), true);
1210 writeOperand(II->getUnwindDest(), true);
1212 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1214 printType(AI->getType()->getElementType());
1215 if (AI->isArrayAllocation()) {
1217 writeOperand(AI->getArraySize(), true);
1219 if (AI->getAlignment()) {
1220 Out << ", align " << AI->getAlignment();
1222 } else if (isa<CastInst>(I)) {
1223 if (Operand) writeOperand(Operand, true); // Work with broken code
1225 printType(I.getType());
1226 } else if (isa<VAArgInst>(I)) {
1227 if (Operand) writeOperand(Operand, true); // Work with broken code
1229 printType(I.getType());
1230 } else if (Operand) { // Print the normal way...
1232 // PrintAllTypes - Instructions who have operands of all the same type
1233 // omit the type from all but the first operand. If the instruction has
1234 // different type operands (for example br), then they are all printed.
1235 bool PrintAllTypes = false;
1236 const Type *TheType = Operand->getType();
1238 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1239 // types even if all operands are bools.
1240 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1241 isa<ShuffleVectorInst>(I)) {
1242 PrintAllTypes = true;
1244 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1245 Operand = I.getOperand(i);
1246 if (Operand->getType() != TheType) {
1247 PrintAllTypes = true; // We have differing types! Print them all!
1253 if (!PrintAllTypes) {
1258 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1260 writeOperand(I.getOperand(i), PrintAllTypes);
1264 printInfoComment(I);
1269 //===----------------------------------------------------------------------===//
1270 // External Interface declarations
1271 //===----------------------------------------------------------------------===//
1273 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1274 SlotMachine SlotTable(this);
1275 AssemblyWriter W(o, SlotTable, this, AAW);
1279 void GlobalVariable::print(std::ostream &o) const {
1280 SlotMachine SlotTable(getParent());
1281 AssemblyWriter W(o, SlotTable, getParent(), 0);
1285 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1286 SlotMachine SlotTable(getParent());
1287 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1292 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1293 WriteAsOperand(o, this, true, 0);
1296 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1297 SlotMachine SlotTable(getParent());
1298 AssemblyWriter W(o, SlotTable,
1299 getParent() ? getParent()->getParent() : 0, AAW);
1303 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1304 const Function *F = getParent() ? getParent()->getParent() : 0;
1305 SlotMachine SlotTable(F);
1306 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1311 void Constant::print(std::ostream &o) const {
1312 if (this == 0) { o << "<null> constant value\n"; return; }
1314 o << ' ' << getType()->getDescription() << ' ';
1316 std::map<const Type *, std::string> TypeTable;
1317 WriteConstantInt(o, this, TypeTable, 0);
1320 void Type::print(std::ostream &o) const {
1324 o << getDescription();
1327 void Argument::print(std::ostream &o) const {
1328 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1331 // Value::dump - allow easy printing of Values from the debugger.
1332 // Located here because so much of the needed functionality is here.
1333 void Value::dump() const { print(std::cerr); llvm_cerr << '\n'; }
1335 // Type::dump - allow easy printing of Values from the debugger.
1336 // Located here because so much of the needed functionality is here.
1337 void Type::dump() const { print(std::cerr); llvm_cerr << '\n'; }
1339 //===----------------------------------------------------------------------===//
1340 // CachedWriter Class Implementation
1341 //===----------------------------------------------------------------------===//
1343 void CachedWriter::setModule(const Module *M) {
1344 delete SC; delete AW;
1346 SC = new SlotMachine(M);
1347 AW = new AssemblyWriter(Out, *SC, M, 0);
1353 CachedWriter::~CachedWriter() {
1358 CachedWriter &CachedWriter::operator<<(const Value &V) {
1359 assert(AW && SC && "CachedWriter does not have a current module!");
1360 if (const Instruction *I = dyn_cast<Instruction>(&V))
1362 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(&V))
1364 else if (const Function *F = dyn_cast<Function>(&V))
1366 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(&V))
1369 AW->writeOperand(&V, true);
1373 CachedWriter& CachedWriter::operator<<(const Type &Ty) {
1374 if (SymbolicTypes) {
1375 const Module *M = AW->getModule();
1376 if (M) WriteTypeSymbolic(Out, &Ty, M);
1383 //===----------------------------------------------------------------------===//
1384 //===-- SlotMachine Implementation
1385 //===----------------------------------------------------------------------===//
1388 #define SC_DEBUG(X) llvm_cerr << X
1393 // Module level constructor. Causes the contents of the Module (sans functions)
1394 // to be added to the slot table.
1395 SlotMachine::SlotMachine(const Module *M)
1396 : TheModule(M) ///< Saved for lazy initialization.
1398 , FunctionProcessed(false)
1402 // Function level constructor. Causes the contents of the Module and the one
1403 // function provided to be added to the slot table.
1404 SlotMachine::SlotMachine(const Function *F)
1405 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1406 , TheFunction(F) ///< Saved for lazy initialization
1407 , FunctionProcessed(false)
1411 inline void SlotMachine::initialize(void) {
1414 TheModule = 0; ///< Prevent re-processing next time we're called.
1416 if (TheFunction && !FunctionProcessed)
1420 // Iterate through all the global variables, functions, and global
1421 // variable initializers and create slots for them.
1422 void SlotMachine::processModule() {
1423 SC_DEBUG("begin processModule!\n");
1425 // Add all of the unnamed global variables to the value table.
1426 for (Module::const_global_iterator I = TheModule->global_begin(),
1427 E = TheModule->global_end(); I != E; ++I)
1431 // Add all the unnamed functions to the table.
1432 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1437 SC_DEBUG("end processModule!\n");
1441 // Process the arguments, basic blocks, and instructions of a function.
1442 void SlotMachine::processFunction() {
1443 SC_DEBUG("begin processFunction!\n");
1445 // Add all the function arguments with no names.
1446 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1447 AE = TheFunction->arg_end(); AI != AE; ++AI)
1449 getOrCreateSlot(AI);
1451 SC_DEBUG("Inserting Instructions:\n");
1453 // Add all of the basic blocks and instructions with no names.
1454 for (Function::const_iterator BB = TheFunction->begin(),
1455 E = TheFunction->end(); BB != E; ++BB) {
1457 getOrCreateSlot(BB);
1458 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1459 if (I->getType() != Type::VoidTy && !I->hasName())
1463 FunctionProcessed = true;
1465 SC_DEBUG("end processFunction!\n");
1468 /// Clean up after incorporating a function. This is the only way to get out of
1469 /// the function incorporation state that affects the
1470 /// getSlot/getOrCreateSlot lock. Function incorporation state is indicated
1471 /// by TheFunction != 0.
1472 void SlotMachine::purgeFunction() {
1473 SC_DEBUG("begin purgeFunction!\n");
1474 fMap.clear(); // Simply discard the function level map
1476 FunctionProcessed = false;
1477 SC_DEBUG("end purgeFunction!\n");
1480 /// Get the slot number for a value. This function will assert if you
1481 /// ask for a Value that hasn't previously been inserted with getOrCreateSlot.
1482 /// Types are forbidden because Type does not inherit from Value (any more).
1483 int SlotMachine::getSlot(const Value *V) {
1484 assert(V && "Can't get slot for null Value");
1485 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1486 "Can't insert a non-GlobalValue Constant into SlotMachine");
1488 // Check for uninitialized state and do lazy initialization
1491 // Get the type of the value
1492 const Type* VTy = V->getType();
1494 // Find the type plane in the module map
1495 TypedPlanes::const_iterator MI = mMap.find(VTy);
1498 // Lookup the type in the function map too
1499 TypedPlanes::const_iterator FI = fMap.find(VTy);
1500 // If there is a corresponding type plane in the function map
1501 if (FI != fMap.end()) {
1502 // Lookup the Value in the function map
1503 ValueMap::const_iterator FVI = FI->second.map.find(V);
1504 // If the value doesn't exist in the function map
1505 if (FVI == FI->second.map.end()) {
1506 // Look up the value in the module map.
1507 if (MI == mMap.end()) return -1;
1508 ValueMap::const_iterator MVI = MI->second.map.find(V);
1509 // If we didn't find it, it wasn't inserted
1510 if (MVI == MI->second.map.end()) return -1;
1511 assert(MVI != MI->second.map.end() && "Value not found");
1512 // We found it only at the module level
1515 // else the value exists in the function map
1517 // Return the slot number as the module's contribution to
1518 // the type plane plus the index in the function's contribution
1519 // to the type plane.
1520 if (MI != mMap.end())
1521 return MI->second.next_slot + FVI->second;
1528 // N.B. Can get here only if either !TheFunction or the function doesn't
1529 // have a corresponding type plane for the Value
1531 // Make sure the type plane exists
1532 if (MI == mMap.end()) return -1;
1533 // Lookup the value in the module's map
1534 ValueMap::const_iterator MVI = MI->second.map.find(V);
1535 // Make sure we found it.
1536 if (MVI == MI->second.map.end()) return -1;
1542 // Create a new slot, or return the existing slot if it is already
1543 // inserted. Note that the logic here parallels getSlot but instead
1544 // of asserting when the Value* isn't found, it inserts the value.
1545 unsigned SlotMachine::getOrCreateSlot(const Value *V) {
1546 const Type* VTy = V->getType();
1547 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1548 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1549 "Can't insert a non-GlobalValue Constant into SlotMachine");
1551 // Look up the type plane for the Value's type from the module map
1552 TypedPlanes::const_iterator MI = mMap.find(VTy);
1555 // Get the type plane for the Value's type from the function map
1556 TypedPlanes::const_iterator FI = fMap.find(VTy);
1557 // If there is a corresponding type plane in the function map
1558 if (FI != fMap.end()) {
1559 // Lookup the Value in the function map
1560 ValueMap::const_iterator FVI = FI->second.map.find(V);
1561 // If the value doesn't exist in the function map
1562 if (FVI == FI->second.map.end()) {
1563 // If there is no corresponding type plane in the module map
1564 if (MI == mMap.end())
1565 return insertValue(V);
1566 // Look up the value in the module map
1567 ValueMap::const_iterator MVI = MI->second.map.find(V);
1568 // If we didn't find it, it wasn't inserted
1569 if (MVI == MI->second.map.end())
1570 return insertValue(V);
1572 // We found it only at the module level
1575 // else the value exists in the function map
1577 if (MI == mMap.end())
1580 // Return the slot number as the module's contribution to
1581 // the type plane plus the index in the function's contribution
1582 // to the type plane.
1583 return MI->second.next_slot + FVI->second;
1586 // else there is not a corresponding type plane in the function map
1588 // If the type plane doesn't exists at the module level
1589 if (MI == mMap.end()) {
1590 return insertValue(V);
1591 // else type plane exists at the module level, examine it
1593 // Look up the value in the module's map
1594 ValueMap::const_iterator MVI = MI->second.map.find(V);
1595 // If we didn't find it there either
1596 if (MVI == MI->second.map.end())
1597 // Return the slot number as the module's contribution to
1598 // the type plane plus the index of the function map insertion.
1599 return MI->second.next_slot + insertValue(V);
1606 // N.B. Can only get here if TheFunction == 0
1608 // If the module map's type plane is not for the Value's type
1609 if (MI != mMap.end()) {
1610 // Lookup the value in the module's map
1611 ValueMap::const_iterator MVI = MI->second.map.find(V);
1612 if (MVI != MI->second.map.end())
1616 return insertValue(V);
1620 // Low level insert function. Minimal checking is done. This
1621 // function is just for the convenience of getOrCreateSlot (above).
1622 unsigned SlotMachine::insertValue(const Value *V) {
1623 assert(V && "Can't insert a null Value into SlotMachine!");
1624 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1625 "Can't insert a non-GlobalValue Constant into SlotMachine");
1626 assert(V->getType() != Type::VoidTy && !V->hasName());
1628 const Type *VTy = V->getType();
1629 unsigned DestSlot = 0;
1632 TypedPlanes::iterator I = fMap.find(VTy);
1633 if (I == fMap.end())
1634 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1635 DestSlot = I->second.map[V] = I->second.next_slot++;
1637 TypedPlanes::iterator I = mMap.find(VTy);
1638 if (I == mMap.end())
1639 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1640 DestSlot = I->second.map[V] = I->second.next_slot++;
1643 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1645 // G = Global, F = Function, o = other
1646 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 'o')));