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);
291 for (StructType::element_iterator I = STy->element_begin(),
292 E = STy->element_end(); I != E; ++I) {
293 if (I != STy->element_begin())
295 calcTypeName(*I, TypeStack, TypeNames, Result);
300 case Type::PointerTyID:
301 calcTypeName(cast<PointerType>(Ty)->getElementType(),
302 TypeStack, TypeNames, Result);
305 case Type::ArrayTyID: {
306 const ArrayType *ATy = cast<ArrayType>(Ty);
307 Result += "[" + utostr(ATy->getNumElements()) + " x ";
308 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
312 case Type::PackedTyID: {
313 const PackedType *PTy = cast<PackedType>(Ty);
314 Result += "<" + utostr(PTy->getNumElements()) + " x ";
315 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
319 case Type::OpaqueTyID:
323 Result += "<unrecognized-type>";
327 TypeStack.pop_back(); // Remove self from stack...
331 /// printTypeInt - The internal guts of printing out a type that has a
332 /// potentially named portion.
334 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
335 std::map<const Type *, std::string> &TypeNames) {
336 // Primitive types always print out their description, regardless of whether
337 // they have been named or not.
339 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
340 return Out << Ty->getDescription();
342 // Check to see if the type is named.
343 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
344 if (I != TypeNames.end()) return Out << I->second;
346 // Otherwise we have a type that has not been named but is a derived type.
347 // Carefully recurse the type hierarchy to print out any contained symbolic
350 std::vector<const Type *> TypeStack;
351 std::string TypeName;
352 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
353 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
354 return (Out << TypeName);
358 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
359 /// type, iff there is an entry in the modules symbol table for the specified
360 /// type or one of it's component types. This is slower than a simple x << Type
362 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
366 // If they want us to print out a type, but there is no context, we can't
367 // print it symbolically.
369 return Out << Ty->getDescription();
371 std::map<const Type *, std::string> TypeNames;
372 fillTypeNameTable(M, TypeNames);
373 return printTypeInt(Out, Ty, TypeNames);
376 // PrintEscapedString - Print each character of the specified string, escaping
377 // it if it is not printable or if it is an escape char.
378 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
379 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
380 unsigned char C = Str[i];
381 if (isprint(C) && C != '"' && C != '\\') {
385 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
386 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
391 static const char *getPredicateText(unsigned predicate) {
392 const char * pred = "unknown";
394 case FCmpInst::FCMP_FALSE: pred = "false"; break;
395 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
396 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
397 case FCmpInst::FCMP_OGE: pred = "oge"; break;
398 case FCmpInst::FCMP_OLT: pred = "olt"; break;
399 case FCmpInst::FCMP_OLE: pred = "ole"; break;
400 case FCmpInst::FCMP_ONE: pred = "one"; break;
401 case FCmpInst::FCMP_ORD: pred = "ord"; break;
402 case FCmpInst::FCMP_UNO: pred = "uno"; break;
403 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
404 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
405 case FCmpInst::FCMP_UGE: pred = "uge"; break;
406 case FCmpInst::FCMP_ULT: pred = "ult"; break;
407 case FCmpInst::FCMP_ULE: pred = "ule"; break;
408 case FCmpInst::FCMP_UNE: pred = "une"; break;
409 case FCmpInst::FCMP_TRUE: pred = "true"; break;
410 case ICmpInst::ICMP_EQ: pred = "eq"; break;
411 case ICmpInst::ICMP_NE: pred = "ne"; break;
412 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
413 case ICmpInst::ICMP_SGE: pred = "sge"; break;
414 case ICmpInst::ICMP_SLT: pred = "slt"; break;
415 case ICmpInst::ICMP_SLE: pred = "sle"; break;
416 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
417 case ICmpInst::ICMP_UGE: pred = "uge"; break;
418 case ICmpInst::ICMP_ULT: pred = "ult"; break;
419 case ICmpInst::ICMP_ULE: pred = "ule"; break;
424 /// @brief Internal constant writer.
425 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
426 std::map<const Type *, std::string> &TypeTable,
427 SlotMachine *Machine) {
428 const int IndentSize = 4;
429 static std::string Indent = "\n";
430 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
431 Out << (CB->getValue() ? "true" : "false");
432 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
433 if (CI->getType()->isSigned())
434 Out << CI->getSExtValue();
436 Out << CI->getZExtValue();
437 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
438 // We would like to output the FP constant value in exponential notation,
439 // but we cannot do this if doing so will lose precision. Check here to
440 // make sure that we only output it in exponential format if we can parse
441 // the value back and get the same value.
443 std::string StrVal = ftostr(CFP->getValue());
445 // Check to make sure that the stringized number is not some string like
446 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
447 // the string matches the "[-+]?[0-9]" regex.
449 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
450 ((StrVal[0] == '-' || StrVal[0] == '+') &&
451 (StrVal[1] >= '0' && StrVal[1] <= '9')))
452 // Reparse stringized version!
453 if (atof(StrVal.c_str()) == CFP->getValue()) {
458 // Otherwise we could not reparse it to exactly the same value, so we must
459 // output the string in hexadecimal format!
460 assert(sizeof(double) == sizeof(uint64_t) &&
461 "assuming that double is 64 bits!");
462 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
464 } else if (isa<ConstantAggregateZero>(CV)) {
465 Out << "zeroinitializer";
466 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
467 // As a special case, print the array as a string if it is an array of
468 // ubytes or an array of sbytes with positive values.
470 const Type *ETy = CA->getType()->getElementType();
471 if (CA->isString()) {
473 PrintEscapedString(CA->getAsString(), Out);
476 } else { // Cannot output in string format...
478 if (CA->getNumOperands()) {
480 printTypeInt(Out, ETy, TypeTable);
481 WriteAsOperandInternal(Out, CA->getOperand(0),
483 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
485 printTypeInt(Out, ETy, TypeTable);
486 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
491 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
493 unsigned N = CS->getNumOperands();
496 Indent += std::string(IndentSize, ' ');
501 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
503 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
505 for (unsigned i = 1; i < N; i++) {
507 if (N > 2) Out << Indent;
508 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
510 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
512 if (N > 2) Indent.resize(Indent.size() - IndentSize);
516 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
517 const Type *ETy = CP->getType()->getElementType();
518 assert(CP->getNumOperands() > 0 &&
519 "Number of operands for a PackedConst must be > 0");
522 printTypeInt(Out, ETy, TypeTable);
523 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
524 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
526 printTypeInt(Out, ETy, TypeTable);
527 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
530 } else if (isa<ConstantPointerNull>(CV)) {
533 } else if (isa<UndefValue>(CV)) {
536 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
537 Out << CE->getOpcodeName();
539 Out << " " << getPredicateText(CE->getPredicate());
542 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
543 printTypeInt(Out, (*OI)->getType(), TypeTable);
544 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
545 if (OI+1 != CE->op_end())
551 printTypeInt(Out, CE->getType(), TypeTable);
557 Out << "<placeholder or erroneous Constant>";
562 /// WriteAsOperand - Write the name of the specified value out to the specified
563 /// ostream. This can be useful when you just want to print int %reg126, not
564 /// the whole instruction that generated it.
566 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
567 std::map<const Type*, std::string> &TypeTable,
568 SlotMachine *Machine) {
571 Out << getLLVMName(V->getName());
573 const Constant *CV = dyn_cast<Constant>(V);
574 if (CV && !isa<GlobalValue>(CV)) {
575 WriteConstantInt(Out, CV, TypeTable, Machine);
576 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
578 if (IA->hasSideEffects())
579 Out << "sideeffect ";
581 PrintEscapedString(IA->getAsmString(), Out);
583 PrintEscapedString(IA->getConstraintString(), Out);
588 Slot = Machine->getSlot(V);
590 Machine = createSlotMachine(V);
592 Slot = Machine->getSlot(V);
605 /// WriteAsOperand - Write the name of the specified value out to the specified
606 /// ostream. This can be useful when you just want to print int %reg126, not
607 /// the whole instruction that generated it.
609 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
610 bool PrintType, const Module *Context) {
611 std::map<const Type *, std::string> TypeNames;
612 if (Context == 0) Context = getModuleFromVal(V);
615 fillTypeNameTable(Context, TypeNames);
618 printTypeInt(Out, V->getType(), TypeNames);
620 WriteAsOperandInternal(Out, V, TypeNames, 0);
627 class AssemblyWriter {
629 SlotMachine &Machine;
630 const Module *TheModule;
631 std::map<const Type *, std::string> TypeNames;
632 AssemblyAnnotationWriter *AnnotationWriter;
634 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
635 AssemblyAnnotationWriter *AAW)
636 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
638 // If the module has a symbol table, take all global types and stuff their
639 // names into the TypeNames map.
641 fillTypeNameTable(M, TypeNames);
644 inline void write(const Module *M) { printModule(M); }
645 inline void write(const GlobalVariable *G) { printGlobal(G); }
646 inline void write(const Function *F) { printFunction(F); }
647 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
648 inline void write(const Instruction *I) { printInstruction(*I); }
649 inline void write(const Constant *CPV) { printConstant(CPV); }
650 inline void write(const Type *Ty) { printType(Ty); }
652 void writeOperand(const Value *Op, bool PrintType);
654 const Module* getModule() { return TheModule; }
657 void printModule(const Module *M);
658 void printSymbolTable(const SymbolTable &ST);
659 void printConstant(const Constant *CPV);
660 void printGlobal(const GlobalVariable *GV);
661 void printFunction(const Function *F);
662 void printArgument(const Argument *FA);
663 void printBasicBlock(const BasicBlock *BB);
664 void printInstruction(const Instruction &I);
666 // printType - Go to extreme measures to attempt to print out a short,
667 // symbolic version of a type name.
669 std::ostream &printType(const Type *Ty) {
670 return printTypeInt(Out, Ty, TypeNames);
673 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
674 // without considering any symbolic types that we may have equal to it.
676 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
678 // printInfoComment - Print a little comment after the instruction indicating
679 // which slot it occupies.
680 void printInfoComment(const Value &V);
682 } // end of llvm namespace
684 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
685 /// without considering any symbolic types that we may have equal to it.
687 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
688 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
689 printType(FTy->getReturnType()) << " (";
690 for (FunctionType::param_iterator I = FTy->param_begin(),
691 E = FTy->param_end(); I != E; ++I) {
692 if (I != FTy->param_begin())
696 if (FTy->isVarArg()) {
697 if (FTy->getNumParams()) Out << ", ";
701 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
703 for (StructType::element_iterator I = STy->element_begin(),
704 E = STy->element_end(); I != E; ++I) {
705 if (I != STy->element_begin())
710 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
711 printType(PTy->getElementType()) << '*';
712 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
713 Out << '[' << ATy->getNumElements() << " x ";
714 printType(ATy->getElementType()) << ']';
715 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
716 Out << '<' << PTy->getNumElements() << " x ";
717 printType(PTy->getElementType()) << '>';
719 else if (isa<OpaqueType>(Ty)) {
722 if (!Ty->isPrimitiveType())
723 Out << "<unknown derived type>";
730 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
732 Out << "<null operand!>";
734 if (PrintType) { Out << ' '; printType(Operand->getType()); }
735 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
740 void AssemblyWriter::printModule(const Module *M) {
741 if (!M->getModuleIdentifier().empty() &&
742 // Don't print the ID if it will start a new line (which would
743 // require a comment char before it).
744 M->getModuleIdentifier().find('\n') == std::string::npos)
745 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
747 if (!M->getDataLayout().empty())
748 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
750 switch (M->getEndianness()) {
751 case Module::LittleEndian: Out << "target endian = little\n"; break;
752 case Module::BigEndian: Out << "target endian = big\n"; break;
753 case Module::AnyEndianness: break;
755 switch (M->getPointerSize()) {
756 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
757 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
758 case Module::AnyPointerSize: break;
760 if (!M->getTargetTriple().empty())
761 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
763 if (!M->getModuleInlineAsm().empty()) {
764 // Split the string into lines, to make it easier to read the .ll file.
765 std::string Asm = M->getModuleInlineAsm();
767 size_t NewLine = Asm.find_first_of('\n', CurPos);
768 while (NewLine != std::string::npos) {
769 // We found a newline, print the portion of the asm string from the
770 // last newline up to this newline.
771 Out << "module asm \"";
772 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
776 NewLine = Asm.find_first_of('\n', CurPos);
778 Out << "module asm \"";
779 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
783 // Loop over the dependent libraries and emit them.
784 Module::lib_iterator LI = M->lib_begin();
785 Module::lib_iterator LE = M->lib_end();
787 Out << "deplibs = [ ";
789 Out << '"' << *LI << '"';
797 // Loop over the symbol table, emitting all named constants.
798 printSymbolTable(M->getSymbolTable());
800 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
804 Out << "\nimplementation ; Functions:\n";
806 // Output all of the functions.
807 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
811 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
812 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
814 if (!GV->hasInitializer())
815 switch (GV->getLinkage()) {
816 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
817 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
818 default: Out << "external "; break;
821 switch (GV->getLinkage()) {
822 case GlobalValue::InternalLinkage: Out << "internal "; break;
823 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
824 case GlobalValue::WeakLinkage: Out << "weak "; break;
825 case GlobalValue::AppendingLinkage: Out << "appending "; break;
826 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
827 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
828 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
829 case GlobalValue::ExternalLinkage: break;
830 case GlobalValue::GhostLinkage:
831 cerr << "GhostLinkage not allowed in AsmWriter!\n";
835 Out << (GV->isConstant() ? "constant " : "global ");
836 printType(GV->getType()->getElementType());
838 if (GV->hasInitializer()) {
839 Constant* C = cast<Constant>(GV->getInitializer());
840 assert(C && "GlobalVar initializer isn't constant?");
841 writeOperand(GV->getInitializer(), false);
844 if (GV->hasSection())
845 Out << ", section \"" << GV->getSection() << '"';
846 if (GV->getAlignment())
847 Out << ", align " << GV->getAlignment();
849 printInfoComment(*GV);
854 // printSymbolTable - Run through symbol table looking for constants
855 // and types. Emit their declarations.
856 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
859 for (SymbolTable::type_const_iterator TI = ST.type_begin();
860 TI != ST.type_end(); ++TI) {
861 Out << "\t" << getLLVMName(TI->first) << " = type ";
863 // Make sure we print out at least one level of the type structure, so
864 // that we do not get %FILE = type %FILE
866 printTypeAtLeastOneLevel(TI->second) << "\n";
869 // Print the constants, in type plane order.
870 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
871 PI != ST.plane_end(); ++PI) {
872 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
873 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
875 for (; VI != VE; ++VI) {
876 const Value* V = VI->second;
877 const Constant *CPV = dyn_cast<Constant>(V) ;
878 if (CPV && !isa<GlobalValue>(V)) {
886 /// printConstant - Print out a constant pool entry...
888 void AssemblyWriter::printConstant(const Constant *CPV) {
889 // Don't print out unnamed constants, they will be inlined
890 if (!CPV->hasName()) return;
893 Out << "\t" << getLLVMName(CPV->getName()) << " =";
895 // Write the value out now.
896 writeOperand(CPV, true);
898 printInfoComment(*CPV);
902 /// printFunction - Print all aspects of a function.
904 void AssemblyWriter::printFunction(const Function *F) {
905 // Print out the return type and name...
908 // Ensure that no local symbols conflict with global symbols.
909 const_cast<Function*>(F)->renameLocalSymbols();
911 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
914 switch (F->getLinkage()) {
915 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
916 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
917 default: Out << "declare ";
920 switch (F->getLinkage()) {
921 case GlobalValue::InternalLinkage: Out << "internal "; break;
922 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
923 case GlobalValue::WeakLinkage: Out << "weak "; break;
924 case GlobalValue::AppendingLinkage: Out << "appending "; break;
925 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
926 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
927 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
928 case GlobalValue::ExternalLinkage: break;
929 case GlobalValue::GhostLinkage:
930 cerr << "GhostLinkage not allowed in AsmWriter!\n";
934 // Print the calling convention.
935 switch (F->getCallingConv()) {
936 case CallingConv::C: break; // default
937 case CallingConv::CSRet: Out << "csretcc "; break;
938 case CallingConv::Fast: Out << "fastcc "; break;
939 case CallingConv::Cold: Out << "coldcc "; break;
940 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
941 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
942 default: Out << "cc" << F->getCallingConv() << " "; break;
945 printType(F->getReturnType()) << ' ';
946 if (!F->getName().empty())
947 Out << getLLVMName(F->getName());
951 Machine.incorporateFunction(F);
953 // Loop over the arguments, printing them...
954 const FunctionType *FT = F->getFunctionType();
956 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
960 // Finish printing arguments...
961 if (FT->isVarArg()) {
962 if (FT->getNumParams()) Out << ", ";
963 Out << "..."; // Output varargs portion of signature!
968 Out << " section \"" << F->getSection() << '"';
969 if (F->getAlignment())
970 Out << " align " << F->getAlignment();
972 if (F->isExternal()) {
977 // Output all of its basic blocks... for the function
978 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
984 Machine.purgeFunction();
987 /// printArgument - This member is called for every argument that is passed into
988 /// the function. Simply print it out
990 void AssemblyWriter::printArgument(const Argument *Arg) {
991 // Insert commas as we go... the first arg doesn't get a comma
992 if (Arg != Arg->getParent()->arg_begin()) Out << ", ";
995 printType(Arg->getType());
997 // Output name, if available...
999 Out << ' ' << getLLVMName(Arg->getName());
1002 /// printBasicBlock - This member is called for each basic block in a method.
1004 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1005 if (BB->hasName()) { // Print out the label if it exists...
1006 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1007 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1008 Out << "\n; <label>:";
1009 int Slot = Machine.getSlot(BB);
1016 if (BB->getParent() == 0)
1017 Out << "\t\t; Error: Block without parent!";
1019 if (BB != &BB->getParent()->front()) { // Not the entry block?
1020 // Output predecessors for the block...
1022 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1025 Out << " No predecessors!";
1028 writeOperand(*PI, false);
1029 for (++PI; PI != PE; ++PI) {
1031 writeOperand(*PI, false);
1039 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1041 // Output all of the instructions in the basic block...
1042 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1043 printInstruction(*I);
1045 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1049 /// printInfoComment - Print a little comment after the instruction indicating
1050 /// which slot it occupies.
1052 void AssemblyWriter::printInfoComment(const Value &V) {
1053 if (V.getType() != Type::VoidTy) {
1055 printType(V.getType()) << '>';
1058 int SlotNum = Machine.getSlot(&V);
1062 Out << ':' << SlotNum; // Print out the def slot taken.
1064 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1068 // This member is called for each Instruction in a function..
1069 void AssemblyWriter::printInstruction(const Instruction &I) {
1070 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1074 // Print out name if it exists...
1076 Out << getLLVMName(I.getName()) << " = ";
1078 // If this is a volatile load or store, print out the volatile marker.
1079 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1080 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1082 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1083 // If this is a call, check if it's a tail call.
1087 // Print out the opcode...
1088 Out << I.getOpcodeName();
1090 // Print out the compare instruction predicates
1091 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1092 Out << " " << getPredicateText(FCI->getPredicate());
1093 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1094 Out << " " << getPredicateText(ICI->getPredicate());
1097 // Print out the type of the operands...
1098 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1100 // Special case conditional branches to swizzle the condition out to the front
1101 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1102 writeOperand(I.getOperand(2), true);
1104 writeOperand(Operand, true);
1106 writeOperand(I.getOperand(1), true);
1108 } else if (isa<SwitchInst>(I)) {
1109 // Special case switch statement to get formatting nice and correct...
1110 writeOperand(Operand , true); Out << ',';
1111 writeOperand(I.getOperand(1), true); Out << " [";
1113 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1115 writeOperand(I.getOperand(op ), true); Out << ',';
1116 writeOperand(I.getOperand(op+1), true);
1119 } else if (isa<PHINode>(I)) {
1121 printType(I.getType());
1124 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1125 if (op) Out << ", ";
1127 writeOperand(I.getOperand(op ), false); Out << ',';
1128 writeOperand(I.getOperand(op+1), false); Out << " ]";
1130 } else if (isa<ReturnInst>(I) && !Operand) {
1132 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1133 // Print the calling convention being used.
1134 switch (CI->getCallingConv()) {
1135 case CallingConv::C: break; // default
1136 case CallingConv::CSRet: Out << " csretcc"; break;
1137 case CallingConv::Fast: Out << " fastcc"; break;
1138 case CallingConv::Cold: Out << " coldcc"; break;
1139 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1140 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1141 default: Out << " cc" << CI->getCallingConv(); break;
1144 const PointerType *PTy = cast<PointerType>(Operand->getType());
1145 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1146 const Type *RetTy = FTy->getReturnType();
1148 // If possible, print out the short form of the call instruction. We can
1149 // only do this if the first argument is a pointer to a nonvararg function,
1150 // and if the return type is not a pointer to a function.
1152 if (!FTy->isVarArg() &&
1153 (!isa<PointerType>(RetTy) ||
1154 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1155 Out << ' '; printType(RetTy);
1156 writeOperand(Operand, false);
1158 writeOperand(Operand, true);
1161 if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true);
1162 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
1164 writeOperand(I.getOperand(op), true);
1168 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1169 const PointerType *PTy = cast<PointerType>(Operand->getType());
1170 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1171 const Type *RetTy = FTy->getReturnType();
1173 // Print the calling convention being used.
1174 switch (II->getCallingConv()) {
1175 case CallingConv::C: break; // default
1176 case CallingConv::CSRet: Out << " csretcc"; break;
1177 case CallingConv::Fast: Out << " fastcc"; break;
1178 case CallingConv::Cold: Out << " coldcc"; break;
1179 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1180 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1181 default: Out << " cc" << II->getCallingConv(); break;
1184 // If possible, print out the short form of the invoke instruction. We can
1185 // only do this if the first argument is a pointer to a nonvararg function,
1186 // and if the return type is not a pointer to a function.
1188 if (!FTy->isVarArg() &&
1189 (!isa<PointerType>(RetTy) ||
1190 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1191 Out << ' '; printType(RetTy);
1192 writeOperand(Operand, false);
1194 writeOperand(Operand, true);
1198 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1199 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1201 writeOperand(I.getOperand(op), true);
1204 Out << " )\n\t\t\tto";
1205 writeOperand(II->getNormalDest(), true);
1207 writeOperand(II->getUnwindDest(), true);
1209 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1211 printType(AI->getType()->getElementType());
1212 if (AI->isArrayAllocation()) {
1214 writeOperand(AI->getArraySize(), true);
1216 if (AI->getAlignment()) {
1217 Out << ", align " << AI->getAlignment();
1219 } else if (isa<CastInst>(I)) {
1220 if (Operand) writeOperand(Operand, true); // Work with broken code
1222 printType(I.getType());
1223 } else if (isa<VAArgInst>(I)) {
1224 if (Operand) writeOperand(Operand, true); // Work with broken code
1226 printType(I.getType());
1227 } else if (Operand) { // Print the normal way...
1229 // PrintAllTypes - Instructions who have operands of all the same type
1230 // omit the type from all but the first operand. If the instruction has
1231 // different type operands (for example br), then they are all printed.
1232 bool PrintAllTypes = false;
1233 const Type *TheType = Operand->getType();
1235 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1236 // types even if all operands are bools.
1237 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1238 isa<ShuffleVectorInst>(I)) {
1239 PrintAllTypes = true;
1241 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1242 Operand = I.getOperand(i);
1243 if (Operand->getType() != TheType) {
1244 PrintAllTypes = true; // We have differing types! Print them all!
1250 if (!PrintAllTypes) {
1255 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1257 writeOperand(I.getOperand(i), PrintAllTypes);
1261 printInfoComment(I);
1266 //===----------------------------------------------------------------------===//
1267 // External Interface declarations
1268 //===----------------------------------------------------------------------===//
1270 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1271 SlotMachine SlotTable(this);
1272 AssemblyWriter W(o, SlotTable, this, AAW);
1276 void GlobalVariable::print(std::ostream &o) const {
1277 SlotMachine SlotTable(getParent());
1278 AssemblyWriter W(o, SlotTable, getParent(), 0);
1282 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1283 SlotMachine SlotTable(getParent());
1284 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1289 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1290 WriteAsOperand(o, this, true, 0);
1293 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1294 SlotMachine SlotTable(getParent());
1295 AssemblyWriter W(o, SlotTable,
1296 getParent() ? getParent()->getParent() : 0, AAW);
1300 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1301 const Function *F = getParent() ? getParent()->getParent() : 0;
1302 SlotMachine SlotTable(F);
1303 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1308 void Constant::print(std::ostream &o) const {
1309 if (this == 0) { o << "<null> constant value\n"; return; }
1311 o << ' ' << getType()->getDescription() << ' ';
1313 std::map<const Type *, std::string> TypeTable;
1314 WriteConstantInt(o, this, TypeTable, 0);
1317 void Type::print(std::ostream &o) const {
1321 o << getDescription();
1324 void Argument::print(std::ostream &o) const {
1325 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1328 // Value::dump - allow easy printing of Values from the debugger.
1329 // Located here because so much of the needed functionality is here.
1330 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1332 // Type::dump - allow easy printing of Values from the debugger.
1333 // Located here because so much of the needed functionality is here.
1334 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1336 //===----------------------------------------------------------------------===//
1337 // SlotMachine Implementation
1338 //===----------------------------------------------------------------------===//
1341 #define SC_DEBUG(X) cerr << X
1346 // Module level constructor. Causes the contents of the Module (sans functions)
1347 // to be added to the slot table.
1348 SlotMachine::SlotMachine(const Module *M)
1349 : TheModule(M) ///< Saved for lazy initialization.
1351 , FunctionProcessed(false)
1355 // Function level constructor. Causes the contents of the Module and the one
1356 // function provided to be added to the slot table.
1357 SlotMachine::SlotMachine(const Function *F)
1358 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1359 , TheFunction(F) ///< Saved for lazy initialization
1360 , FunctionProcessed(false)
1364 inline void SlotMachine::initialize(void) {
1367 TheModule = 0; ///< Prevent re-processing next time we're called.
1369 if (TheFunction && !FunctionProcessed)
1373 // Iterate through all the global variables, functions, and global
1374 // variable initializers and create slots for them.
1375 void SlotMachine::processModule() {
1376 SC_DEBUG("begin processModule!\n");
1378 // Add all of the unnamed global variables to the value table.
1379 for (Module::const_global_iterator I = TheModule->global_begin(),
1380 E = TheModule->global_end(); I != E; ++I)
1384 // Add all the unnamed functions to the table.
1385 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1390 SC_DEBUG("end processModule!\n");
1394 // Process the arguments, basic blocks, and instructions of a function.
1395 void SlotMachine::processFunction() {
1396 SC_DEBUG("begin processFunction!\n");
1398 // Add all the function arguments with no names.
1399 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1400 AE = TheFunction->arg_end(); AI != AE; ++AI)
1402 getOrCreateSlot(AI);
1404 SC_DEBUG("Inserting Instructions:\n");
1406 // Add all of the basic blocks and instructions with no names.
1407 for (Function::const_iterator BB = TheFunction->begin(),
1408 E = TheFunction->end(); BB != E; ++BB) {
1410 getOrCreateSlot(BB);
1411 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1412 if (I->getType() != Type::VoidTy && !I->hasName())
1416 FunctionProcessed = true;
1418 SC_DEBUG("end processFunction!\n");
1421 /// Clean up after incorporating a function. This is the only way to get out of
1422 /// the function incorporation state that affects the
1423 /// getSlot/getOrCreateSlot lock. Function incorporation state is indicated
1424 /// by TheFunction != 0.
1425 void SlotMachine::purgeFunction() {
1426 SC_DEBUG("begin purgeFunction!\n");
1427 fMap.clear(); // Simply discard the function level map
1429 FunctionProcessed = false;
1430 SC_DEBUG("end purgeFunction!\n");
1433 /// Get the slot number for a value. This function will assert if you
1434 /// ask for a Value that hasn't previously been inserted with getOrCreateSlot.
1435 /// Types are forbidden because Type does not inherit from Value (any more).
1436 int SlotMachine::getSlot(const Value *V) {
1437 assert(V && "Can't get slot for null Value");
1438 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1439 "Can't insert a non-GlobalValue Constant into SlotMachine");
1441 // Check for uninitialized state and do lazy initialization
1444 // Get the type of the value
1445 const Type* VTy = V->getType();
1447 // Find the type plane in the module map
1448 TypedPlanes::const_iterator MI = mMap.find(VTy);
1451 // Lookup the type in the function map too
1452 TypedPlanes::const_iterator FI = fMap.find(VTy);
1453 // If there is a corresponding type plane in the function map
1454 if (FI != fMap.end()) {
1455 // Lookup the Value in the function map
1456 ValueMap::const_iterator FVI = FI->second.map.find(V);
1457 // If the value doesn't exist in the function map
1458 if (FVI == FI->second.map.end()) {
1459 // Look up the value in the module map.
1460 if (MI == mMap.end()) return -1;
1461 ValueMap::const_iterator MVI = MI->second.map.find(V);
1462 // If we didn't find it, it wasn't inserted
1463 if (MVI == MI->second.map.end()) return -1;
1464 assert(MVI != MI->second.map.end() && "Value not found");
1465 // We found it only at the module level
1468 // else the value exists in the function map
1470 // Return the slot number as the module's contribution to
1471 // the type plane plus the index in the function's contribution
1472 // to the type plane.
1473 if (MI != mMap.end())
1474 return MI->second.next_slot + FVI->second;
1481 // N.B. Can get here only if either !TheFunction or the function doesn't
1482 // have a corresponding type plane for the Value
1484 // Make sure the type plane exists
1485 if (MI == mMap.end()) return -1;
1486 // Lookup the value in the module's map
1487 ValueMap::const_iterator MVI = MI->second.map.find(V);
1488 // Make sure we found it.
1489 if (MVI == MI->second.map.end()) return -1;
1495 // Create a new slot, or return the existing slot if it is already
1496 // inserted. Note that the logic here parallels getSlot but instead
1497 // of asserting when the Value* isn't found, it inserts the value.
1498 unsigned SlotMachine::getOrCreateSlot(const Value *V) {
1499 const Type* VTy = V->getType();
1500 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1501 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1502 "Can't insert a non-GlobalValue Constant into SlotMachine");
1504 // Look up the type plane for the Value's type from the module map
1505 TypedPlanes::const_iterator MI = mMap.find(VTy);
1508 // Get the type plane for the Value's type from the function map
1509 TypedPlanes::const_iterator FI = fMap.find(VTy);
1510 // If there is a corresponding type plane in the function map
1511 if (FI != fMap.end()) {
1512 // Lookup the Value in the function map
1513 ValueMap::const_iterator FVI = FI->second.map.find(V);
1514 // If the value doesn't exist in the function map
1515 if (FVI == FI->second.map.end()) {
1516 // If there is no corresponding type plane in the module map
1517 if (MI == mMap.end())
1518 return insertValue(V);
1519 // Look up the value in the module map
1520 ValueMap::const_iterator MVI = MI->second.map.find(V);
1521 // If we didn't find it, it wasn't inserted
1522 if (MVI == MI->second.map.end())
1523 return insertValue(V);
1525 // We found it only at the module level
1528 // else the value exists in the function map
1530 if (MI == mMap.end())
1533 // Return the slot number as the module's contribution to
1534 // the type plane plus the index in the function's contribution
1535 // to the type plane.
1536 return MI->second.next_slot + FVI->second;
1539 // else there is not a corresponding type plane in the function map
1541 // If the type plane doesn't exists at the module level
1542 if (MI == mMap.end()) {
1543 return insertValue(V);
1544 // else type plane exists at the module level, examine it
1546 // Look up the value in the module's map
1547 ValueMap::const_iterator MVI = MI->second.map.find(V);
1548 // If we didn't find it there either
1549 if (MVI == MI->second.map.end())
1550 // Return the slot number as the module's contribution to
1551 // the type plane plus the index of the function map insertion.
1552 return MI->second.next_slot + insertValue(V);
1559 // N.B. Can only get here if TheFunction == 0
1561 // If the module map's type plane is not for the Value's type
1562 if (MI != mMap.end()) {
1563 // Lookup the value in the module's map
1564 ValueMap::const_iterator MVI = MI->second.map.find(V);
1565 if (MVI != MI->second.map.end())
1569 return insertValue(V);
1573 // Low level insert function. Minimal checking is done. This
1574 // function is just for the convenience of getOrCreateSlot (above).
1575 unsigned SlotMachine::insertValue(const Value *V) {
1576 assert(V && "Can't insert a null Value into SlotMachine!");
1577 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1578 "Can't insert a non-GlobalValue Constant into SlotMachine");
1579 assert(V->getType() != Type::VoidTy && !V->hasName());
1581 const Type *VTy = V->getType();
1582 unsigned DestSlot = 0;
1585 TypedPlanes::iterator I = fMap.find(VTy);
1586 if (I == fMap.end())
1587 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1588 DestSlot = I->second.map[V] = I->second.next_slot++;
1590 TypedPlanes::iterator I = mMap.find(VTy);
1591 if (I == mMap.end())
1592 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1593 DestSlot = I->second.map[V] = I->second.next_slot++;
1596 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1598 // G = Global, F = Function, o = other
1599 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 'o')));