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);
274 if (FTy->getParamAttrs(0)) {
276 Result += FunctionType::getParamAttrsText(FTy->getParamAttrs(0));
280 for (FunctionType::param_iterator I = FTy->param_begin(),
281 E = FTy->param_end(); I != E; ++I) {
282 if (I != FTy->param_begin())
284 calcTypeName(*I, TypeStack, TypeNames, Result);
285 if (FTy->getParamAttrs(Idx)) {
287 Result += FunctionType::getParamAttrsText(FTy->getParamAttrs(Idx));
291 if (FTy->isVarArg()) {
292 if (FTy->getNumParams()) Result += ", ";
298 case Type::StructTyID: {
299 const StructType *STy = cast<StructType>(Ty);
303 for (StructType::element_iterator I = STy->element_begin(),
304 E = STy->element_end(); I != E; ++I) {
305 if (I != STy->element_begin())
307 calcTypeName(*I, TypeStack, TypeNames, Result);
314 case Type::PointerTyID:
315 calcTypeName(cast<PointerType>(Ty)->getElementType(),
316 TypeStack, TypeNames, Result);
319 case Type::ArrayTyID: {
320 const ArrayType *ATy = cast<ArrayType>(Ty);
321 Result += "[" + utostr(ATy->getNumElements()) + " x ";
322 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
326 case Type::PackedTyID: {
327 const PackedType *PTy = cast<PackedType>(Ty);
328 Result += "<" + utostr(PTy->getNumElements()) + " x ";
329 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
333 case Type::OpaqueTyID:
337 Result += "<unrecognized-type>";
341 TypeStack.pop_back(); // Remove self from stack...
345 /// printTypeInt - The internal guts of printing out a type that has a
346 /// potentially named portion.
348 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
349 std::map<const Type *, std::string> &TypeNames) {
350 // Primitive types always print out their description, regardless of whether
351 // they have been named or not.
353 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
354 return Out << Ty->getDescription();
356 // Check to see if the type is named.
357 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
358 if (I != TypeNames.end()) return Out << I->second;
360 // Otherwise we have a type that has not been named but is a derived type.
361 // Carefully recurse the type hierarchy to print out any contained symbolic
364 std::vector<const Type *> TypeStack;
365 std::string TypeName;
366 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
367 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
368 return (Out << TypeName);
372 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
373 /// type, iff there is an entry in the modules symbol table for the specified
374 /// type or one of it's component types. This is slower than a simple x << Type
376 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
380 // If they want us to print out a type, but there is no context, we can't
381 // print it symbolically.
383 return Out << Ty->getDescription();
385 std::map<const Type *, std::string> TypeNames;
386 fillTypeNameTable(M, TypeNames);
387 return printTypeInt(Out, Ty, TypeNames);
390 // PrintEscapedString - Print each character of the specified string, escaping
391 // it if it is not printable or if it is an escape char.
392 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
393 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
394 unsigned char C = Str[i];
395 if (isprint(C) && C != '"' && C != '\\') {
399 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
400 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
405 static const char *getPredicateText(unsigned predicate) {
406 const char * pred = "unknown";
408 case FCmpInst::FCMP_FALSE: pred = "false"; break;
409 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
410 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
411 case FCmpInst::FCMP_OGE: pred = "oge"; break;
412 case FCmpInst::FCMP_OLT: pred = "olt"; break;
413 case FCmpInst::FCMP_OLE: pred = "ole"; break;
414 case FCmpInst::FCMP_ONE: pred = "one"; break;
415 case FCmpInst::FCMP_ORD: pred = "ord"; break;
416 case FCmpInst::FCMP_UNO: pred = "uno"; break;
417 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
418 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
419 case FCmpInst::FCMP_UGE: pred = "uge"; break;
420 case FCmpInst::FCMP_ULT: pred = "ult"; break;
421 case FCmpInst::FCMP_ULE: pred = "ule"; break;
422 case FCmpInst::FCMP_UNE: pred = "une"; break;
423 case FCmpInst::FCMP_TRUE: pred = "true"; break;
424 case ICmpInst::ICMP_EQ: pred = "eq"; break;
425 case ICmpInst::ICMP_NE: pred = "ne"; break;
426 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
427 case ICmpInst::ICMP_SGE: pred = "sge"; break;
428 case ICmpInst::ICMP_SLT: pred = "slt"; break;
429 case ICmpInst::ICMP_SLE: pred = "sle"; break;
430 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
431 case ICmpInst::ICMP_UGE: pred = "uge"; break;
432 case ICmpInst::ICMP_ULT: pred = "ult"; break;
433 case ICmpInst::ICMP_ULE: pred = "ule"; break;
438 /// @brief Internal constant writer.
439 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
440 std::map<const Type *, std::string> &TypeTable,
441 SlotMachine *Machine) {
442 const int IndentSize = 4;
443 static std::string Indent = "\n";
444 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
445 Out << (CB->getValue() ? "true" : "false");
446 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
447 Out << CI->getSExtValue();
448 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
449 // We would like to output the FP constant value in exponential notation,
450 // but we cannot do this if doing so will lose precision. Check here to
451 // make sure that we only output it in exponential format if we can parse
452 // the value back and get the same value.
454 std::string StrVal = ftostr(CFP->getValue());
456 // Check to make sure that the stringized number is not some string like
457 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
458 // the string matches the "[-+]?[0-9]" regex.
460 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
461 ((StrVal[0] == '-' || StrVal[0] == '+') &&
462 (StrVal[1] >= '0' && StrVal[1] <= '9')))
463 // Reparse stringized version!
464 if (atof(StrVal.c_str()) == CFP->getValue()) {
469 // Otherwise we could not reparse it to exactly the same value, so we must
470 // output the string in hexadecimal format!
471 assert(sizeof(double) == sizeof(uint64_t) &&
472 "assuming that double is 64 bits!");
473 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
475 } else if (isa<ConstantAggregateZero>(CV)) {
476 Out << "zeroinitializer";
477 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
478 // As a special case, print the array as a string if it is an array of
479 // ubytes or an array of sbytes with positive values.
481 const Type *ETy = CA->getType()->getElementType();
482 if (CA->isString()) {
484 PrintEscapedString(CA->getAsString(), Out);
487 } else { // Cannot output in string format...
489 if (CA->getNumOperands()) {
491 printTypeInt(Out, ETy, TypeTable);
492 WriteAsOperandInternal(Out, CA->getOperand(0),
494 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
496 printTypeInt(Out, ETy, TypeTable);
497 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
502 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
504 unsigned N = CS->getNumOperands();
507 Indent += std::string(IndentSize, ' ');
512 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
514 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
516 for (unsigned i = 1; i < N; i++) {
518 if (N > 2) Out << Indent;
519 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
521 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
523 if (N > 2) Indent.resize(Indent.size() - IndentSize);
527 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
528 const Type *ETy = CP->getType()->getElementType();
529 assert(CP->getNumOperands() > 0 &&
530 "Number of operands for a PackedConst must be > 0");
533 printTypeInt(Out, ETy, TypeTable);
534 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
535 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
537 printTypeInt(Out, ETy, TypeTable);
538 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
541 } else if (isa<ConstantPointerNull>(CV)) {
544 } else if (isa<UndefValue>(CV)) {
547 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
548 Out << CE->getOpcodeName();
550 Out << " " << getPredicateText(CE->getPredicate());
553 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
554 printTypeInt(Out, (*OI)->getType(), TypeTable);
555 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
556 if (OI+1 != CE->op_end())
562 printTypeInt(Out, CE->getType(), TypeTable);
568 Out << "<placeholder or erroneous Constant>";
573 /// WriteAsOperand - Write the name of the specified value out to the specified
574 /// ostream. This can be useful when you just want to print int %reg126, not
575 /// the whole instruction that generated it.
577 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
578 std::map<const Type*, std::string> &TypeTable,
579 SlotMachine *Machine) {
582 Out << getLLVMName(V->getName());
584 const Constant *CV = dyn_cast<Constant>(V);
585 if (CV && !isa<GlobalValue>(CV)) {
586 WriteConstantInt(Out, CV, TypeTable, Machine);
587 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
589 if (IA->hasSideEffects())
590 Out << "sideeffect ";
592 PrintEscapedString(IA->getAsmString(), Out);
594 PrintEscapedString(IA->getConstraintString(), Out);
599 Slot = Machine->getSlot(V);
601 Machine = createSlotMachine(V);
603 Slot = Machine->getSlot(V);
616 /// WriteAsOperand - Write the name of the specified value out to the specified
617 /// ostream. This can be useful when you just want to print int %reg126, not
618 /// the whole instruction that generated it.
620 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
621 bool PrintType, const Module *Context) {
622 std::map<const Type *, std::string> TypeNames;
623 if (Context == 0) Context = getModuleFromVal(V);
626 fillTypeNameTable(Context, TypeNames);
629 printTypeInt(Out, V->getType(), TypeNames);
631 WriteAsOperandInternal(Out, V, TypeNames, 0);
638 class AssemblyWriter {
640 SlotMachine &Machine;
641 const Module *TheModule;
642 std::map<const Type *, std::string> TypeNames;
643 AssemblyAnnotationWriter *AnnotationWriter;
645 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
646 AssemblyAnnotationWriter *AAW)
647 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
649 // If the module has a symbol table, take all global types and stuff their
650 // names into the TypeNames map.
652 fillTypeNameTable(M, TypeNames);
655 inline void write(const Module *M) { printModule(M); }
656 inline void write(const GlobalVariable *G) { printGlobal(G); }
657 inline void write(const Function *F) { printFunction(F); }
658 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
659 inline void write(const Instruction *I) { printInstruction(*I); }
660 inline void write(const Constant *CPV) { printConstant(CPV); }
661 inline void write(const Type *Ty) { printType(Ty); }
663 void writeOperand(const Value *Op, bool PrintType);
665 const Module* getModule() { return TheModule; }
668 void printModule(const Module *M);
669 void printSymbolTable(const SymbolTable &ST);
670 void printConstant(const Constant *CPV);
671 void printGlobal(const GlobalVariable *GV);
672 void printFunction(const Function *F);
673 void printArgument(const Argument *FA, FunctionType::ParameterAttributes A);
674 void printBasicBlock(const BasicBlock *BB);
675 void printInstruction(const Instruction &I);
677 // printType - Go to extreme measures to attempt to print out a short,
678 // symbolic version of a type name.
680 std::ostream &printType(const Type *Ty) {
681 return printTypeInt(Out, Ty, TypeNames);
684 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
685 // without considering any symbolic types that we may have equal to it.
687 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
689 // printInfoComment - Print a little comment after the instruction indicating
690 // which slot it occupies.
691 void printInfoComment(const Value &V);
693 } // end of llvm namespace
695 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
696 /// without considering any symbolic types that we may have equal to it.
698 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
699 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
700 printType(FTy->getReturnType());
701 if (FTy->getParamAttrs(0))
702 Out << ' ' << FunctionType::getParamAttrsText(FTy->getParamAttrs(0));
705 for (FunctionType::param_iterator I = FTy->param_begin(),
706 E = FTy->param_end(); I != E; ++I) {
707 if (I != FTy->param_begin())
710 if (FTy->getParamAttrs(Idx)) {
711 Out << " " << FunctionType::getParamAttrsText(FTy->getParamAttrs(Idx));
715 if (FTy->isVarArg()) {
716 if (FTy->getNumParams()) Out << ", ";
720 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
724 for (StructType::element_iterator I = STy->element_begin(),
725 E = STy->element_end(); I != E; ++I) {
726 if (I != STy->element_begin())
733 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
734 printType(PTy->getElementType()) << '*';
735 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
736 Out << '[' << ATy->getNumElements() << " x ";
737 printType(ATy->getElementType()) << ']';
738 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
739 Out << '<' << PTy->getNumElements() << " x ";
740 printType(PTy->getElementType()) << '>';
742 else if (isa<OpaqueType>(Ty)) {
745 if (!Ty->isPrimitiveType())
746 Out << "<unknown derived type>";
753 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
755 Out << "<null operand!>";
757 if (PrintType) { Out << ' '; printType(Operand->getType()); }
758 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
763 void AssemblyWriter::printModule(const Module *M) {
764 if (!M->getModuleIdentifier().empty() &&
765 // Don't print the ID if it will start a new line (which would
766 // require a comment char before it).
767 M->getModuleIdentifier().find('\n') == std::string::npos)
768 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
770 if (!M->getDataLayout().empty())
771 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
773 switch (M->getEndianness()) {
774 case Module::LittleEndian: Out << "target endian = little\n"; break;
775 case Module::BigEndian: Out << "target endian = big\n"; break;
776 case Module::AnyEndianness: break;
778 switch (M->getPointerSize()) {
779 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
780 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
781 case Module::AnyPointerSize: break;
783 if (!M->getTargetTriple().empty())
784 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
786 if (!M->getModuleInlineAsm().empty()) {
787 // Split the string into lines, to make it easier to read the .ll file.
788 std::string Asm = M->getModuleInlineAsm();
790 size_t NewLine = Asm.find_first_of('\n', CurPos);
791 while (NewLine != std::string::npos) {
792 // We found a newline, print the portion of the asm string from the
793 // last newline up to this newline.
794 Out << "module asm \"";
795 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
799 NewLine = Asm.find_first_of('\n', CurPos);
801 Out << "module asm \"";
802 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
806 // Loop over the dependent libraries and emit them.
807 Module::lib_iterator LI = M->lib_begin();
808 Module::lib_iterator LE = M->lib_end();
810 Out << "deplibs = [ ";
812 Out << '"' << *LI << '"';
820 // Loop over the symbol table, emitting all named constants.
821 printSymbolTable(M->getSymbolTable());
823 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
827 Out << "\nimplementation ; Functions:\n";
829 // Output all of the functions.
830 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
834 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
835 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
837 if (!GV->hasInitializer())
838 switch (GV->getLinkage()) {
839 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
840 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
841 default: Out << "external "; break;
844 switch (GV->getLinkage()) {
845 case GlobalValue::InternalLinkage: Out << "internal "; break;
846 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
847 case GlobalValue::WeakLinkage: Out << "weak "; break;
848 case GlobalValue::AppendingLinkage: Out << "appending "; break;
849 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
850 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
851 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
852 case GlobalValue::ExternalLinkage: break;
853 case GlobalValue::GhostLinkage:
854 cerr << "GhostLinkage not allowed in AsmWriter!\n";
858 Out << (GV->isConstant() ? "constant " : "global ");
859 printType(GV->getType()->getElementType());
861 if (GV->hasInitializer()) {
862 Constant* C = cast<Constant>(GV->getInitializer());
863 assert(C && "GlobalVar initializer isn't constant?");
864 writeOperand(GV->getInitializer(), false);
867 if (GV->hasSection())
868 Out << ", section \"" << GV->getSection() << '"';
869 if (GV->getAlignment())
870 Out << ", align " << GV->getAlignment();
872 printInfoComment(*GV);
877 // printSymbolTable - Run through symbol table looking for constants
878 // and types. Emit their declarations.
879 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
882 for (SymbolTable::type_const_iterator TI = ST.type_begin();
883 TI != ST.type_end(); ++TI) {
884 Out << "\t" << getLLVMName(TI->first) << " = type ";
886 // Make sure we print out at least one level of the type structure, so
887 // that we do not get %FILE = type %FILE
889 printTypeAtLeastOneLevel(TI->second) << "\n";
892 // Print the constants, in type plane order.
893 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
894 PI != ST.plane_end(); ++PI) {
895 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
896 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
898 for (; VI != VE; ++VI) {
899 const Value* V = VI->second;
900 const Constant *CPV = dyn_cast<Constant>(V) ;
901 if (CPV && !isa<GlobalValue>(V)) {
909 /// printConstant - Print out a constant pool entry...
911 void AssemblyWriter::printConstant(const Constant *CPV) {
912 // Don't print out unnamed constants, they will be inlined
913 if (!CPV->hasName()) return;
916 Out << "\t" << getLLVMName(CPV->getName()) << " =";
918 // Write the value out now.
919 writeOperand(CPV, true);
921 printInfoComment(*CPV);
925 /// printFunction - Print all aspects of a function.
927 void AssemblyWriter::printFunction(const Function *F) {
928 // Print out the return type and name...
931 // Ensure that no local symbols conflict with global symbols.
932 const_cast<Function*>(F)->renameLocalSymbols();
934 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
937 switch (F->getLinkage()) {
938 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
939 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
940 default: Out << "declare ";
944 switch (F->getLinkage()) {
945 case GlobalValue::InternalLinkage: Out << "internal "; break;
946 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
947 case GlobalValue::WeakLinkage: Out << "weak "; break;
948 case GlobalValue::AppendingLinkage: Out << "appending "; break;
949 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
950 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
951 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
952 case GlobalValue::ExternalLinkage: break;
953 case GlobalValue::GhostLinkage:
954 cerr << "GhostLinkage not allowed in AsmWriter!\n";
959 // Print the calling convention.
960 switch (F->getCallingConv()) {
961 case CallingConv::C: break; // default
962 case CallingConv::CSRet: Out << "csretcc "; break;
963 case CallingConv::Fast: Out << "fastcc "; break;
964 case CallingConv::Cold: Out << "coldcc "; break;
965 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
966 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
967 default: Out << "cc" << F->getCallingConv() << " "; break;
970 const FunctionType *FT = F->getFunctionType();
971 printType(F->getReturnType()) << ' ';
972 if (FT->getParamAttrs(0))
973 Out << FunctionType::getParamAttrsText(FT->getParamAttrs(0)) << ' ';
974 if (!F->getName().empty())
975 Out << getLLVMName(F->getName());
979 Machine.incorporateFunction(F);
981 // Loop over the arguments, printing them...
984 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
986 // Insert commas as we go... the first arg doesn't get a comma
987 if (I != F->arg_begin()) Out << ", ";
988 printArgument(I, FT->getParamAttrs(Idx));
992 // Finish printing arguments...
993 if (FT->isVarArg()) {
994 if (FT->getNumParams()) Out << ", ";
995 Out << "..."; // Output varargs portion of signature!
1000 Out << " section \"" << F->getSection() << '"';
1001 if (F->getAlignment())
1002 Out << " align " << F->getAlignment();
1004 if (F->isExternal()) {
1009 // Output all of its basic blocks... for the function
1010 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1016 Machine.purgeFunction();
1019 /// printArgument - This member is called for every argument that is passed into
1020 /// the function. Simply print it out
1022 void AssemblyWriter::printArgument(const Argument *Arg,
1023 FunctionType::ParameterAttributes attrs) {
1025 printType(Arg->getType());
1027 if (attrs != FunctionType::NoAttributeSet)
1028 Out << ' ' << FunctionType::getParamAttrsText(attrs);
1030 // Output name, if available...
1032 Out << ' ' << getLLVMName(Arg->getName());
1035 /// printBasicBlock - This member is called for each basic block in a method.
1037 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1038 if (BB->hasName()) { // Print out the label if it exists...
1039 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1040 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1041 Out << "\n; <label>:";
1042 int Slot = Machine.getSlot(BB);
1049 if (BB->getParent() == 0)
1050 Out << "\t\t; Error: Block without parent!";
1052 if (BB != &BB->getParent()->front()) { // Not the entry block?
1053 // Output predecessors for the block...
1055 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1058 Out << " No predecessors!";
1061 writeOperand(*PI, false);
1062 for (++PI; PI != PE; ++PI) {
1064 writeOperand(*PI, false);
1072 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1074 // Output all of the instructions in the basic block...
1075 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1076 printInstruction(*I);
1078 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1082 /// printInfoComment - Print a little comment after the instruction indicating
1083 /// which slot it occupies.
1085 void AssemblyWriter::printInfoComment(const Value &V) {
1086 if (V.getType() != Type::VoidTy) {
1088 printType(V.getType()) << '>';
1091 int SlotNum = Machine.getSlot(&V);
1095 Out << ':' << SlotNum; // Print out the def slot taken.
1097 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1101 // This member is called for each Instruction in a function..
1102 void AssemblyWriter::printInstruction(const Instruction &I) {
1103 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1107 // Print out name if it exists...
1109 Out << getLLVMName(I.getName()) << " = ";
1111 // If this is a volatile load or store, print out the volatile marker.
1112 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1113 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1115 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1116 // If this is a call, check if it's a tail call.
1120 // Print out the opcode...
1121 Out << I.getOpcodeName();
1123 // Print out the compare instruction predicates
1124 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1125 Out << " " << getPredicateText(FCI->getPredicate());
1126 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1127 Out << " " << getPredicateText(ICI->getPredicate());
1130 // Print out the type of the operands...
1131 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1133 // Special case conditional branches to swizzle the condition out to the front
1134 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1135 writeOperand(I.getOperand(2), true);
1137 writeOperand(Operand, true);
1139 writeOperand(I.getOperand(1), true);
1141 } else if (isa<SwitchInst>(I)) {
1142 // Special case switch statement to get formatting nice and correct...
1143 writeOperand(Operand , true); Out << ',';
1144 writeOperand(I.getOperand(1), true); Out << " [";
1146 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1148 writeOperand(I.getOperand(op ), true); Out << ',';
1149 writeOperand(I.getOperand(op+1), true);
1152 } else if (isa<PHINode>(I)) {
1154 printType(I.getType());
1157 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1158 if (op) Out << ", ";
1160 writeOperand(I.getOperand(op ), false); Out << ',';
1161 writeOperand(I.getOperand(op+1), false); Out << " ]";
1163 } else if (isa<ReturnInst>(I) && !Operand) {
1165 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1166 // Print the calling convention being used.
1167 switch (CI->getCallingConv()) {
1168 case CallingConv::C: break; // default
1169 case CallingConv::CSRet: Out << " csretcc"; break;
1170 case CallingConv::Fast: Out << " fastcc"; break;
1171 case CallingConv::Cold: Out << " coldcc"; break;
1172 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1173 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1174 default: Out << " cc" << CI->getCallingConv(); break;
1177 const PointerType *PTy = cast<PointerType>(Operand->getType());
1178 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1179 const Type *RetTy = FTy->getReturnType();
1181 // If possible, print out the short form of the call instruction. We can
1182 // only do this if the first argument is a pointer to a nonvararg function,
1183 // and if the return type is not a pointer to a function.
1185 if (!FTy->isVarArg() &&
1186 (!isa<PointerType>(RetTy) ||
1187 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1188 Out << ' '; printType(RetTy);
1189 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet)
1190 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(0));
1191 writeOperand(Operand, false);
1193 writeOperand(Operand, true);
1196 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1199 writeOperand(I.getOperand(op), true);
1200 if (FTy->getParamAttrs(op) != FunctionType::NoAttributeSet)
1201 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op));
1204 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1205 const PointerType *PTy = cast<PointerType>(Operand->getType());
1206 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1207 const Type *RetTy = FTy->getReturnType();
1209 // Print the calling convention being used.
1210 switch (II->getCallingConv()) {
1211 case CallingConv::C: break; // default
1212 case CallingConv::CSRet: Out << " csretcc"; break;
1213 case CallingConv::Fast: Out << " fastcc"; break;
1214 case CallingConv::Cold: Out << " coldcc"; break;
1215 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1216 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1217 default: Out << " cc" << II->getCallingConv(); break;
1220 // If possible, print out the short form of the invoke instruction. We can
1221 // only do this if the first argument is a pointer to a nonvararg function,
1222 // and if the return type is not a pointer to a function.
1224 if (!FTy->isVarArg() &&
1225 (!isa<PointerType>(RetTy) ||
1226 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1227 Out << ' '; printType(RetTy);
1228 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet)
1229 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(0));
1230 writeOperand(Operand, false);
1232 writeOperand(Operand, true);
1236 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1239 writeOperand(I.getOperand(op), true);
1240 if (FTy->getParamAttrs(op-2) != FunctionType::NoAttributeSet)
1241 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op-2));
1244 Out << " )\n\t\t\tto";
1245 writeOperand(II->getNormalDest(), true);
1247 writeOperand(II->getUnwindDest(), true);
1249 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1251 printType(AI->getType()->getElementType());
1252 if (AI->isArrayAllocation()) {
1254 writeOperand(AI->getArraySize(), true);
1256 if (AI->getAlignment()) {
1257 Out << ", align " << AI->getAlignment();
1259 } else if (isa<CastInst>(I)) {
1260 if (Operand) writeOperand(Operand, true); // Work with broken code
1262 printType(I.getType());
1263 } else if (isa<VAArgInst>(I)) {
1264 if (Operand) writeOperand(Operand, true); // Work with broken code
1266 printType(I.getType());
1267 } else if (Operand) { // Print the normal way...
1269 // PrintAllTypes - Instructions who have operands of all the same type
1270 // omit the type from all but the first operand. If the instruction has
1271 // different type operands (for example br), then they are all printed.
1272 bool PrintAllTypes = false;
1273 const Type *TheType = Operand->getType();
1275 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1276 // types even if all operands are bools.
1277 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1278 isa<ShuffleVectorInst>(I)) {
1279 PrintAllTypes = true;
1281 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1282 Operand = I.getOperand(i);
1283 if (Operand->getType() != TheType) {
1284 PrintAllTypes = true; // We have differing types! Print them all!
1290 if (!PrintAllTypes) {
1295 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1297 writeOperand(I.getOperand(i), PrintAllTypes);
1301 printInfoComment(I);
1306 //===----------------------------------------------------------------------===//
1307 // External Interface declarations
1308 //===----------------------------------------------------------------------===//
1310 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1311 SlotMachine SlotTable(this);
1312 AssemblyWriter W(o, SlotTable, this, AAW);
1316 void GlobalVariable::print(std::ostream &o) const {
1317 SlotMachine SlotTable(getParent());
1318 AssemblyWriter W(o, SlotTable, getParent(), 0);
1322 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1323 SlotMachine SlotTable(getParent());
1324 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1329 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1330 WriteAsOperand(o, this, true, 0);
1333 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1334 SlotMachine SlotTable(getParent());
1335 AssemblyWriter W(o, SlotTable,
1336 getParent() ? getParent()->getParent() : 0, AAW);
1340 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1341 const Function *F = getParent() ? getParent()->getParent() : 0;
1342 SlotMachine SlotTable(F);
1343 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1348 void Constant::print(std::ostream &o) const {
1349 if (this == 0) { o << "<null> constant value\n"; return; }
1351 o << ' ' << getType()->getDescription() << ' ';
1353 std::map<const Type *, std::string> TypeTable;
1354 WriteConstantInt(o, this, TypeTable, 0);
1357 void Type::print(std::ostream &o) const {
1361 o << getDescription();
1364 void Argument::print(std::ostream &o) const {
1365 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1368 // Value::dump - allow easy printing of Values from the debugger.
1369 // Located here because so much of the needed functionality is here.
1370 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1372 // Type::dump - allow easy printing of Values from the debugger.
1373 // Located here because so much of the needed functionality is here.
1374 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1376 //===----------------------------------------------------------------------===//
1377 // SlotMachine Implementation
1378 //===----------------------------------------------------------------------===//
1381 #define SC_DEBUG(X) cerr << X
1386 // Module level constructor. Causes the contents of the Module (sans functions)
1387 // to be added to the slot table.
1388 SlotMachine::SlotMachine(const Module *M)
1389 : TheModule(M) ///< Saved for lazy initialization.
1391 , FunctionProcessed(false)
1395 // Function level constructor. Causes the contents of the Module and the one
1396 // function provided to be added to the slot table.
1397 SlotMachine::SlotMachine(const Function *F)
1398 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1399 , TheFunction(F) ///< Saved for lazy initialization
1400 , FunctionProcessed(false)
1404 inline void SlotMachine::initialize(void) {
1407 TheModule = 0; ///< Prevent re-processing next time we're called.
1409 if (TheFunction && !FunctionProcessed)
1413 // Iterate through all the global variables, functions, and global
1414 // variable initializers and create slots for them.
1415 void SlotMachine::processModule() {
1416 SC_DEBUG("begin processModule!\n");
1418 // Add all of the unnamed global variables to the value table.
1419 for (Module::const_global_iterator I = TheModule->global_begin(),
1420 E = TheModule->global_end(); I != E; ++I)
1424 // Add all the unnamed functions to the table.
1425 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1430 SC_DEBUG("end processModule!\n");
1434 // Process the arguments, basic blocks, and instructions of a function.
1435 void SlotMachine::processFunction() {
1436 SC_DEBUG("begin processFunction!\n");
1438 // Add all the function arguments with no names.
1439 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1440 AE = TheFunction->arg_end(); AI != AE; ++AI)
1442 getOrCreateSlot(AI);
1444 SC_DEBUG("Inserting Instructions:\n");
1446 // Add all of the basic blocks and instructions with no names.
1447 for (Function::const_iterator BB = TheFunction->begin(),
1448 E = TheFunction->end(); BB != E; ++BB) {
1450 getOrCreateSlot(BB);
1451 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1452 if (I->getType() != Type::VoidTy && !I->hasName())
1456 FunctionProcessed = true;
1458 SC_DEBUG("end processFunction!\n");
1461 /// Clean up after incorporating a function. This is the only way to get out of
1462 /// the function incorporation state that affects the
1463 /// getSlot/getOrCreateSlot lock. Function incorporation state is indicated
1464 /// by TheFunction != 0.
1465 void SlotMachine::purgeFunction() {
1466 SC_DEBUG("begin purgeFunction!\n");
1467 fMap.clear(); // Simply discard the function level map
1469 FunctionProcessed = false;
1470 SC_DEBUG("end purgeFunction!\n");
1473 /// Get the slot number for a value. This function will assert if you
1474 /// ask for a Value that hasn't previously been inserted with getOrCreateSlot.
1475 /// Types are forbidden because Type does not inherit from Value (any more).
1476 int SlotMachine::getSlot(const Value *V) {
1477 assert(V && "Can't get slot for null Value");
1478 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1479 "Can't insert a non-GlobalValue Constant into SlotMachine");
1481 // Check for uninitialized state and do lazy initialization
1484 // Get the type of the value
1485 const Type* VTy = V->getType();
1487 // Find the type plane in the module map
1488 TypedPlanes::const_iterator MI = mMap.find(VTy);
1491 // Lookup the type in the function map too
1492 TypedPlanes::const_iterator FI = fMap.find(VTy);
1493 // If there is a corresponding type plane in the function map
1494 if (FI != fMap.end()) {
1495 // Lookup the Value in the function map
1496 ValueMap::const_iterator FVI = FI->second.map.find(V);
1497 // If the value doesn't exist in the function map
1498 if (FVI == FI->second.map.end()) {
1499 // Look up the value in the module map.
1500 if (MI == mMap.end()) return -1;
1501 ValueMap::const_iterator MVI = MI->second.map.find(V);
1502 // If we didn't find it, it wasn't inserted
1503 if (MVI == MI->second.map.end()) return -1;
1504 assert(MVI != MI->second.map.end() && "Value not found");
1505 // We found it only at the module level
1508 // else the value exists in the function map
1510 // Return the slot number as the module's contribution to
1511 // the type plane plus the index in the function's contribution
1512 // to the type plane.
1513 if (MI != mMap.end())
1514 return MI->second.next_slot + FVI->second;
1521 // N.B. Can get here only if either !TheFunction or the function doesn't
1522 // have a corresponding type plane for the Value
1524 // Make sure the type plane exists
1525 if (MI == mMap.end()) return -1;
1526 // Lookup the value in the module's map
1527 ValueMap::const_iterator MVI = MI->second.map.find(V);
1528 // Make sure we found it.
1529 if (MVI == MI->second.map.end()) return -1;
1535 // Create a new slot, or return the existing slot if it is already
1536 // inserted. Note that the logic here parallels getSlot but instead
1537 // of asserting when the Value* isn't found, it inserts the value.
1538 unsigned SlotMachine::getOrCreateSlot(const Value *V) {
1539 const Type* VTy = V->getType();
1540 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1541 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1542 "Can't insert a non-GlobalValue Constant into SlotMachine");
1544 // Look up the type plane for the Value's type from the module map
1545 TypedPlanes::const_iterator MI = mMap.find(VTy);
1548 // Get the type plane for the Value's type from the function map
1549 TypedPlanes::const_iterator FI = fMap.find(VTy);
1550 // If there is a corresponding type plane in the function map
1551 if (FI != fMap.end()) {
1552 // Lookup the Value in the function map
1553 ValueMap::const_iterator FVI = FI->second.map.find(V);
1554 // If the value doesn't exist in the function map
1555 if (FVI == FI->second.map.end()) {
1556 // If there is no corresponding type plane in the module map
1557 if (MI == mMap.end())
1558 return insertValue(V);
1559 // Look up the value in the module map
1560 ValueMap::const_iterator MVI = MI->second.map.find(V);
1561 // If we didn't find it, it wasn't inserted
1562 if (MVI == MI->second.map.end())
1563 return insertValue(V);
1565 // We found it only at the module level
1568 // else the value exists in the function map
1570 if (MI == mMap.end())
1573 // Return the slot number as the module's contribution to
1574 // the type plane plus the index in the function's contribution
1575 // to the type plane.
1576 return MI->second.next_slot + FVI->second;
1579 // else there is not a corresponding type plane in the function map
1581 // If the type plane doesn't exists at the module level
1582 if (MI == mMap.end()) {
1583 return insertValue(V);
1584 // else type plane exists at the module level, examine it
1586 // Look up the value in the module's map
1587 ValueMap::const_iterator MVI = MI->second.map.find(V);
1588 // If we didn't find it there either
1589 if (MVI == MI->second.map.end())
1590 // Return the slot number as the module's contribution to
1591 // the type plane plus the index of the function map insertion.
1592 return MI->second.next_slot + insertValue(V);
1599 // N.B. Can only get here if TheFunction == 0
1601 // If the module map's type plane is not for the Value's type
1602 if (MI != mMap.end()) {
1603 // Lookup the value in the module's map
1604 ValueMap::const_iterator MVI = MI->second.map.find(V);
1605 if (MVI != MI->second.map.end())
1609 return insertValue(V);
1613 // Low level insert function. Minimal checking is done. This
1614 // function is just for the convenience of getOrCreateSlot (above).
1615 unsigned SlotMachine::insertValue(const Value *V) {
1616 assert(V && "Can't insert a null Value into SlotMachine!");
1617 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1618 "Can't insert a non-GlobalValue Constant into SlotMachine");
1619 assert(V->getType() != Type::VoidTy && !V->hasName());
1621 const Type *VTy = V->getType();
1622 unsigned DestSlot = 0;
1625 TypedPlanes::iterator I = fMap.find(VTy);
1626 if (I == fMap.end())
1627 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1628 DestSlot = I->second.map[V] = I->second.next_slot++;
1630 TypedPlanes::iterator I = mMap.find(VTy);
1631 if (I == mMap.end())
1632 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1633 DestSlot = I->second.map[V] = I->second.next_slot++;
1636 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1638 // G = Global, F = Function, o = other
1639 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 'o')));