1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Assembly/CachedWriter.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/Assembly/AsmAnnotationWriter.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instruction.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Module.h"
28 #include "llvm/SymbolTable.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Streams.h"
39 // Make virtual table appear in this compilation unit.
40 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
42 /// This class provides computation of slot numbers for LLVM Assembly writing.
43 /// @brief LLVM Assembly Writing Slot Computation.
50 /// @brief A mapping of Values to slot numbers
51 typedef std::map<const Value*, unsigned> ValueMap;
52 typedef std::map<const Type*, unsigned> TypeMap;
54 /// @brief A plane with next slot number and ValueMap
56 unsigned next_slot; ///< The next slot number to use
57 ValueMap map; ///< The map of Value* -> unsigned
58 ValuePlane() { next_slot = 0; } ///< Make sure we start at 0
64 TypePlane() { next_slot = 0; }
65 void clear() { map.clear(); next_slot = 0; }
68 /// @brief The map of planes by Type
69 typedef std::map<const Type*, ValuePlane> TypedPlanes;
72 /// @name Constructors
75 /// @brief Construct from a module
76 SlotMachine(const Module *M );
78 /// @brief Construct from a function, starting out in incorp state.
79 SlotMachine(const Function *F );
85 /// Return the slot number of the specified value in it's type
86 /// plane. Its an error to ask for something not in the SlotMachine.
87 /// Its an error to ask for a Type*
88 int getSlot(const Value *V);
89 int getSlot(const Type*Ty);
91 /// Determine if a Value has a slot or not
92 bool hasSlot(const Value* V);
93 bool hasSlot(const Type* Ty);
99 /// If you'd like to deal with a function instead of just a module, use
100 /// this method to get its data into the SlotMachine.
101 void incorporateFunction(const Function *F) {
103 FunctionProcessed = false;
106 /// After calling incorporateFunction, use this method to remove the
107 /// most recently incorporated function from the SlotMachine. This
108 /// will reset the state of the machine back to just the module contents.
109 void purgeFunction();
112 /// @name Implementation Details
115 /// This function does the actual initialization.
116 inline void initialize();
118 /// Values can be crammed into here at will. If they haven't
119 /// been inserted already, they get inserted, otherwise they are ignored.
120 /// Either way, the slot number for the Value* is returned.
121 unsigned createSlot(const Value *V);
122 unsigned createSlot(const Type* Ty);
124 /// Insert a value into the value table. Return the slot number
125 /// that it now occupies. BadThings(TM) will happen if you insert a
126 /// Value that's already been inserted.
127 unsigned insertValue( const Value *V );
128 unsigned insertValue( const Type* Ty);
130 /// Add all of the module level global variables (and their initializers)
131 /// and function declarations, but not the contents of those functions.
132 void processModule();
134 /// Add all of the functions arguments, basic blocks, and instructions
135 void processFunction();
137 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
138 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
145 /// @brief The module for which we are holding slot numbers
146 const Module* TheModule;
148 /// @brief The function for which we are holding slot numbers
149 const Function* TheFunction;
150 bool FunctionProcessed;
152 /// @brief The TypePlanes map for the module level data
156 /// @brief The TypePlanes map for the function level data
164 } // end namespace llvm
166 static RegisterPass<PrintModulePass>
167 X("printm", "Print module to stderr");
168 static RegisterPass<PrintFunctionPass>
169 Y("print","Print function to stderr");
171 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
173 std::map<const Type *, std::string> &TypeTable,
174 SlotMachine *Machine);
176 static void WriteAsOperandInternal(std::ostream &Out, const Type *T,
178 std::map<const Type *, std::string> &TypeTable,
179 SlotMachine *Machine);
181 static const Module *getModuleFromVal(const Value *V) {
182 if (const Argument *MA = dyn_cast<Argument>(V))
183 return MA->getParent() ? MA->getParent()->getParent() : 0;
184 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
185 return BB->getParent() ? BB->getParent()->getParent() : 0;
186 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
187 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
188 return M ? M->getParent() : 0;
189 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
190 return GV->getParent();
194 static SlotMachine *createSlotMachine(const Value *V) {
195 if (const Argument *FA = dyn_cast<Argument>(V)) {
196 return new SlotMachine(FA->getParent());
197 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
198 return new SlotMachine(I->getParent()->getParent());
199 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
200 return new SlotMachine(BB->getParent());
201 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
202 return new SlotMachine(GV->getParent());
203 } else if (const Function *Func = dyn_cast<Function>(V)) {
204 return new SlotMachine(Func);
209 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
210 // prefixed with % (if the string only contains simple characters) or is
211 // surrounded with ""'s (if it has special chars in it).
212 static std::string getLLVMName(const std::string &Name,
213 bool prefixName = true) {
214 assert(!Name.empty() && "Cannot get empty name!");
216 // First character cannot start with a number...
217 if (Name[0] >= '0' && Name[0] <= '9')
218 return "\"" + Name + "\"";
220 // Scan to see if we have any characters that are not on the "white list"
221 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
223 assert(C != '"' && "Illegal character in LLVM value name!");
224 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
225 C != '-' && C != '.' && C != '_')
226 return "\"" + Name + "\"";
229 // If we get here, then the identifier is legal to use as a "VarID".
237 /// fillTypeNameTable - If the module has a symbol table, take all global types
238 /// and stuff their names into the TypeNames map.
240 static void fillTypeNameTable(const Module *M,
241 std::map<const Type *, std::string> &TypeNames) {
243 const SymbolTable &ST = M->getSymbolTable();
244 SymbolTable::type_const_iterator TI = ST.type_begin();
245 for (; TI != ST.type_end(); ++TI ) {
246 // As a heuristic, don't insert pointer to primitive types, because
247 // they are used too often to have a single useful name.
249 const Type *Ty = cast<Type>(TI->second);
250 if (!isa<PointerType>(Ty) ||
251 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
252 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
253 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
259 static void calcTypeName(const Type *Ty,
260 std::vector<const Type *> &TypeStack,
261 std::map<const Type *, std::string> &TypeNames,
262 std::string & Result){
263 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
264 Result += Ty->getDescription(); // Base case
268 // Check to see if the type is named.
269 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
270 if (I != TypeNames.end()) {
275 if (isa<OpaqueType>(Ty)) {
280 // Check to see if the Type is already on the stack...
281 unsigned Slot = 0, CurSize = TypeStack.size();
282 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
284 // This is another base case for the recursion. In this case, we know
285 // that we have looped back to a type that we have previously visited.
286 // Generate the appropriate upreference to handle this.
287 if (Slot < CurSize) {
288 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
292 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
294 switch (Ty->getTypeID()) {
295 case Type::FunctionTyID: {
296 const FunctionType *FTy = cast<FunctionType>(Ty);
297 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
299 for (FunctionType::param_iterator I = FTy->param_begin(),
300 E = FTy->param_end(); I != E; ++I) {
301 if (I != FTy->param_begin())
303 calcTypeName(*I, TypeStack, TypeNames, Result);
305 if (FTy->isVarArg()) {
306 if (FTy->getNumParams()) Result += ", ";
312 case Type::StructTyID: {
313 const StructType *STy = cast<StructType>(Ty);
315 for (StructType::element_iterator I = STy->element_begin(),
316 E = STy->element_end(); I != E; ++I) {
317 if (I != STy->element_begin())
319 calcTypeName(*I, TypeStack, TypeNames, Result);
324 case Type::PointerTyID:
325 calcTypeName(cast<PointerType>(Ty)->getElementType(),
326 TypeStack, TypeNames, Result);
329 case Type::ArrayTyID: {
330 const ArrayType *ATy = cast<ArrayType>(Ty);
331 Result += "[" + utostr(ATy->getNumElements()) + " x ";
332 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
336 case Type::PackedTyID: {
337 const PackedType *PTy = cast<PackedType>(Ty);
338 Result += "<" + utostr(PTy->getNumElements()) + " x ";
339 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
343 case Type::OpaqueTyID:
347 Result += "<unrecognized-type>";
350 TypeStack.pop_back(); // Remove self from stack...
355 /// printTypeInt - The internal guts of printing out a type that has a
356 /// potentially named portion.
358 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
359 std::map<const Type *, std::string> &TypeNames) {
360 // Primitive types always print out their description, regardless of whether
361 // they have been named or not.
363 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
364 return Out << Ty->getDescription();
366 // Check to see if the type is named.
367 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
368 if (I != TypeNames.end()) return Out << I->second;
370 // Otherwise we have a type that has not been named but is a derived type.
371 // Carefully recurse the type hierarchy to print out any contained symbolic
374 std::vector<const Type *> TypeStack;
375 std::string TypeName;
376 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
377 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
378 return (Out << TypeName);
382 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
383 /// type, iff there is an entry in the modules symbol table for the specified
384 /// type or one of it's component types. This is slower than a simple x << Type
386 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
390 // If they want us to print out a type, attempt to make it symbolic if there
391 // is a symbol table in the module...
393 std::map<const Type *, std::string> TypeNames;
394 fillTypeNameTable(M, TypeNames);
396 return printTypeInt(Out, Ty, TypeNames);
398 return Out << Ty->getDescription();
402 // PrintEscapedString - Print each character of the specified string, escaping
403 // it if it is not printable or if it is an escape char.
404 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
405 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
406 unsigned char C = Str[i];
407 if (isprint(C) && C != '"' && C != '\\') {
411 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
412 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
417 static const char * getPredicateText(unsigned predicate) {
418 const char * pred = "unknown";
420 case FCmpInst::FCMP_FALSE: pred = "false"; break;
421 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
422 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
423 case FCmpInst::FCMP_OGE: pred = "oge"; break;
424 case FCmpInst::FCMP_OLT: pred = "olt"; break;
425 case FCmpInst::FCMP_OLE: pred = "ole"; break;
426 case FCmpInst::FCMP_ONE: pred = "one"; break;
427 case FCmpInst::FCMP_ORD: pred = "ord"; break;
428 case FCmpInst::FCMP_UNO: pred = "uno"; break;
429 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
430 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
431 case FCmpInst::FCMP_UGE: pred = "uge"; break;
432 case FCmpInst::FCMP_ULT: pred = "ult"; break;
433 case FCmpInst::FCMP_ULE: pred = "ule"; break;
434 case FCmpInst::FCMP_UNE: pred = "une"; break;
435 case FCmpInst::FCMP_TRUE: pred = "true"; break;
436 case ICmpInst::ICMP_EQ: pred = "eq"; break;
437 case ICmpInst::ICMP_NE: pred = "ne"; break;
438 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
439 case ICmpInst::ICMP_SGE: pred = "sge"; break;
440 case ICmpInst::ICMP_SLT: pred = "slt"; break;
441 case ICmpInst::ICMP_SLE: pred = "sle"; break;
442 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
443 case ICmpInst::ICMP_UGE: pred = "uge"; break;
444 case ICmpInst::ICMP_ULT: pred = "ult"; break;
445 case ICmpInst::ICMP_ULE: pred = "ule"; break;
450 /// @brief Internal constant writer.
451 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
453 std::map<const Type *, std::string> &TypeTable,
454 SlotMachine *Machine) {
455 const int IndentSize = 4;
456 static std::string Indent = "\n";
457 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
458 Out << (CB->getValue() ? "true" : "false");
459 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
460 if (CI->getType()->isSigned())
461 Out << CI->getSExtValue();
463 Out << CI->getZExtValue();
464 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
465 // We would like to output the FP constant value in exponential notation,
466 // but we cannot do this if doing so will lose precision. Check here to
467 // make sure that we only output it in exponential format if we can parse
468 // the value back and get the same value.
470 std::string StrVal = ftostr(CFP->getValue());
472 // Check to make sure that the stringized number is not some string like
473 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
474 // the string matches the "[-+]?[0-9]" regex.
476 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
477 ((StrVal[0] == '-' || StrVal[0] == '+') &&
478 (StrVal[1] >= '0' && StrVal[1] <= '9')))
479 // Reparse stringized version!
480 if (atof(StrVal.c_str()) == CFP->getValue()) {
485 // Otherwise we could not reparse it to exactly the same value, so we must
486 // output the string in hexadecimal format!
487 assert(sizeof(double) == sizeof(uint64_t) &&
488 "assuming that double is 64 bits!");
489 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
491 } else if (isa<ConstantAggregateZero>(CV)) {
492 Out << "zeroinitializer";
493 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
494 // As a special case, print the array as a string if it is an array of
495 // ubytes or an array of sbytes with positive values.
497 const Type *ETy = CA->getType()->getElementType();
498 if (CA->isString()) {
500 PrintEscapedString(CA->getAsString(), Out);
503 } else { // Cannot output in string format...
505 if (CA->getNumOperands()) {
507 printTypeInt(Out, ETy, TypeTable);
508 WriteAsOperandInternal(Out, CA->getOperand(0),
509 PrintName, TypeTable, Machine);
510 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
512 printTypeInt(Out, ETy, TypeTable);
513 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
519 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
521 unsigned N = CS->getNumOperands();
524 Indent += std::string(IndentSize, ' ');
529 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
531 WriteAsOperandInternal(Out, CS->getOperand(0),
532 PrintName, TypeTable, Machine);
534 for (unsigned i = 1; i < N; i++) {
536 if (N > 2) Out << Indent;
537 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
539 WriteAsOperandInternal(Out, CS->getOperand(i),
540 PrintName, TypeTable, Machine);
542 if (N > 2) Indent.resize(Indent.size() - IndentSize);
546 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
547 const Type *ETy = CP->getType()->getElementType();
548 assert(CP->getNumOperands() > 0 &&
549 "Number of operands for a PackedConst must be > 0");
552 printTypeInt(Out, ETy, TypeTable);
553 WriteAsOperandInternal(Out, CP->getOperand(0),
554 PrintName, TypeTable, Machine);
555 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
557 printTypeInt(Out, ETy, TypeTable);
558 WriteAsOperandInternal(Out, CP->getOperand(i), PrintName,
562 } else if (isa<ConstantPointerNull>(CV)) {
565 } else if (isa<UndefValue>(CV)) {
568 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
569 Out << CE->getOpcodeName();
571 Out << " " << getPredicateText(CE->getPredicate());
574 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
575 printTypeInt(Out, (*OI)->getType(), TypeTable);
576 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
577 if (OI+1 != CE->op_end())
583 printTypeInt(Out, CE->getType(), TypeTable);
589 Out << "<placeholder or erroneous Constant>";
594 /// WriteAsOperand - Write the name of the specified value out to the specified
595 /// ostream. This can be useful when you just want to print int %reg126, not
596 /// the whole instruction that generated it.
598 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
600 std::map<const Type*, std::string> &TypeTable,
601 SlotMachine *Machine) {
603 if ((PrintName || isa<GlobalValue>(V)) && V->hasName())
604 Out << getLLVMName(V->getName());
606 const Constant *CV = dyn_cast<Constant>(V);
607 if (CV && !isa<GlobalValue>(CV)) {
608 WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
609 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
611 if (IA->hasSideEffects())
612 Out << "sideeffect ";
614 PrintEscapedString(IA->getAsmString(), Out);
616 PrintEscapedString(IA->getConstraintString(), Out);
621 Slot = Machine->getSlot(V);
623 Machine = createSlotMachine(V);
625 Slot = Machine->getSlot(V);
638 /// WriteAsOperand - Write the name of the specified value out to the specified
639 /// ostream. This can be useful when you just want to print int %reg126, not
640 /// the whole instruction that generated it.
642 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
643 bool PrintType, bool PrintName,
644 const Module *Context) {
645 std::map<const Type *, std::string> TypeNames;
646 if (Context == 0) Context = getModuleFromVal(V);
649 fillTypeNameTable(Context, TypeNames);
652 printTypeInt(Out, V->getType(), TypeNames);
654 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
658 /// WriteAsOperandInternal - Write the name of the specified value out to
659 /// the specified ostream. This can be useful when you just want to print
660 /// int %reg126, not the whole instruction that generated it.
662 static void WriteAsOperandInternal(std::ostream &Out, const Type *T,
664 std::map<const Type*, std::string> &TypeTable,
665 SlotMachine *Machine) {
669 Slot = Machine->getSlot(T);
675 Out << T->getDescription();
679 /// WriteAsOperand - Write the name of the specified value out to the specified
680 /// ostream. This can be useful when you just want to print int %reg126, not
681 /// the whole instruction that generated it.
683 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Type *Ty,
684 bool PrintType, bool PrintName,
685 const Module *Context) {
686 std::map<const Type *, std::string> TypeNames;
687 assert(Context != 0 && "Can't write types as operand without module context");
689 fillTypeNameTable(Context, TypeNames);
692 // printTypeInt(Out, V->getType(), TypeNames);
694 printTypeInt(Out, Ty, TypeNames);
696 WriteAsOperandInternal(Out, Ty, PrintName, TypeNames, 0);
702 class AssemblyWriter {
704 SlotMachine &Machine;
705 const Module *TheModule;
706 std::map<const Type *, std::string> TypeNames;
707 AssemblyAnnotationWriter *AnnotationWriter;
709 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
710 AssemblyAnnotationWriter *AAW)
711 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
713 // If the module has a symbol table, take all global types and stuff their
714 // names into the TypeNames map.
716 fillTypeNameTable(M, TypeNames);
719 inline void write(const Module *M) { printModule(M); }
720 inline void write(const GlobalVariable *G) { printGlobal(G); }
721 inline void write(const Function *F) { printFunction(F); }
722 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
723 inline void write(const Instruction *I) { printInstruction(*I); }
724 inline void write(const Constant *CPV) { printConstant(CPV); }
725 inline void write(const Type *Ty) { printType(Ty); }
727 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
729 const Module* getModule() { return TheModule; }
732 void printModule(const Module *M);
733 void printSymbolTable(const SymbolTable &ST);
734 void printConstant(const Constant *CPV);
735 void printGlobal(const GlobalVariable *GV);
736 void printFunction(const Function *F);
737 void printArgument(const Argument *FA);
738 void printBasicBlock(const BasicBlock *BB);
739 void printInstruction(const Instruction &I);
741 // printType - Go to extreme measures to attempt to print out a short,
742 // symbolic version of a type name.
744 std::ostream &printType(const Type *Ty) {
745 return printTypeInt(Out, Ty, TypeNames);
748 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
749 // without considering any symbolic types that we may have equal to it.
751 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
753 // printInfoComment - Print a little comment after the instruction indicating
754 // which slot it occupies.
755 void printInfoComment(const Value &V);
757 } // end of llvm namespace
759 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
760 /// without considering any symbolic types that we may have equal to it.
762 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
763 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
764 printType(FTy->getReturnType()) << " (";
765 for (FunctionType::param_iterator I = FTy->param_begin(),
766 E = FTy->param_end(); I != E; ++I) {
767 if (I != FTy->param_begin())
771 if (FTy->isVarArg()) {
772 if (FTy->getNumParams()) Out << ", ";
776 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
778 for (StructType::element_iterator I = STy->element_begin(),
779 E = STy->element_end(); I != E; ++I) {
780 if (I != STy->element_begin())
785 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
786 printType(PTy->getElementType()) << '*';
787 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
788 Out << '[' << ATy->getNumElements() << " x ";
789 printType(ATy->getElementType()) << ']';
790 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
791 Out << '<' << PTy->getNumElements() << " x ";
792 printType(PTy->getElementType()) << '>';
794 else if (isa<OpaqueType>(Ty)) {
797 if (!Ty->isPrimitiveType())
798 Out << "<unknown derived type>";
805 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
808 if (PrintType) { Out << ' '; printType(Operand->getType()); }
809 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Machine);
811 Out << "<null operand!>";
816 void AssemblyWriter::printModule(const Module *M) {
817 if (!M->getModuleIdentifier().empty() &&
818 // Don't print the ID if it will start a new line (which would
819 // require a comment char before it).
820 M->getModuleIdentifier().find('\n') == std::string::npos)
821 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
823 if (!M->getDataLayout().empty())
824 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
826 switch (M->getEndianness()) {
827 case Module::LittleEndian: Out << "target endian = little\n"; break;
828 case Module::BigEndian: Out << "target endian = big\n"; break;
829 case Module::AnyEndianness: break;
831 switch (M->getPointerSize()) {
832 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
833 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
834 case Module::AnyPointerSize: break;
836 if (!M->getTargetTriple().empty())
837 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
839 if (!M->getModuleInlineAsm().empty()) {
840 // Split the string into lines, to make it easier to read the .ll file.
841 std::string Asm = M->getModuleInlineAsm();
843 size_t NewLine = Asm.find_first_of('\n', CurPos);
844 while (NewLine != std::string::npos) {
845 // We found a newline, print the portion of the asm string from the
846 // last newline up to this newline.
847 Out << "module asm \"";
848 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
852 NewLine = Asm.find_first_of('\n', CurPos);
854 Out << "module asm \"";
855 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
859 // Loop over the dependent libraries and emit them.
860 Module::lib_iterator LI = M->lib_begin();
861 Module::lib_iterator LE = M->lib_end();
863 Out << "deplibs = [ ";
865 Out << '"' << *LI << '"';
873 // Loop over the symbol table, emitting all named constants.
874 printSymbolTable(M->getSymbolTable());
876 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
880 Out << "\nimplementation ; Functions:\n";
882 // Output all of the functions.
883 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
887 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
888 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
890 if (!GV->hasInitializer())
891 switch (GV->getLinkage()) {
892 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
893 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
894 default: Out << "external "; break;
897 switch (GV->getLinkage()) {
898 case GlobalValue::InternalLinkage: Out << "internal "; break;
899 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
900 case GlobalValue::WeakLinkage: Out << "weak "; break;
901 case GlobalValue::AppendingLinkage: Out << "appending "; break;
902 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
903 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
904 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
905 case GlobalValue::ExternalLinkage: break;
906 case GlobalValue::GhostLinkage:
907 llvm_cerr << "GhostLinkage not allowed in AsmWriter!\n";
911 Out << (GV->isConstant() ? "constant " : "global ");
912 printType(GV->getType()->getElementType());
914 if (GV->hasInitializer()) {
915 Constant* C = cast<Constant>(GV->getInitializer());
916 assert(C && "GlobalVar initializer isn't constant?");
917 writeOperand(GV->getInitializer(), false, isa<GlobalValue>(C));
920 if (GV->hasSection())
921 Out << ", section \"" << GV->getSection() << '"';
922 if (GV->getAlignment())
923 Out << ", align " << GV->getAlignment();
925 printInfoComment(*GV);
930 // printSymbolTable - Run through symbol table looking for constants
931 // and types. Emit their declarations.
932 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
935 for (SymbolTable::type_const_iterator TI = ST.type_begin();
936 TI != ST.type_end(); ++TI ) {
937 Out << "\t" << getLLVMName(TI->first) << " = type ";
939 // Make sure we print out at least one level of the type structure, so
940 // that we do not get %FILE = type %FILE
942 printTypeAtLeastOneLevel(TI->second) << "\n";
945 // Print the constants, in type plane order.
946 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
947 PI != ST.plane_end(); ++PI ) {
948 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
949 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
951 for (; VI != VE; ++VI) {
952 const Value* V = VI->second;
953 const Constant *CPV = dyn_cast<Constant>(V) ;
954 if (CPV && !isa<GlobalValue>(V)) {
962 /// printConstant - Print out a constant pool entry...
964 void AssemblyWriter::printConstant(const Constant *CPV) {
965 // Don't print out unnamed constants, they will be inlined
966 if (!CPV->hasName()) return;
969 Out << "\t" << getLLVMName(CPV->getName()) << " =";
971 // Write the value out now...
972 writeOperand(CPV, true, false);
974 printInfoComment(*CPV);
978 /// printFunction - Print all aspects of a function.
980 void AssemblyWriter::printFunction(const Function *F) {
981 // Print out the return type and name...
984 // Ensure that no local symbols conflict with global symbols.
985 const_cast<Function*>(F)->renameLocalSymbols();
987 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
990 switch (F->getLinkage()) {
991 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
992 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
993 default: Out << "declare ";
996 switch (F->getLinkage()) {
997 case GlobalValue::InternalLinkage: Out << "internal "; break;
998 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
999 case GlobalValue::WeakLinkage: Out << "weak "; break;
1000 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1001 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1002 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1003 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1004 case GlobalValue::ExternalLinkage: break;
1005 case GlobalValue::GhostLinkage:
1006 llvm_cerr << "GhostLinkage not allowed in AsmWriter!\n";
1010 // Print the calling convention.
1011 switch (F->getCallingConv()) {
1012 case CallingConv::C: break; // default
1013 case CallingConv::CSRet: Out << "csretcc "; break;
1014 case CallingConv::Fast: Out << "fastcc "; break;
1015 case CallingConv::Cold: Out << "coldcc "; break;
1016 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1017 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1018 default: Out << "cc" << F->getCallingConv() << " "; break;
1021 printType(F->getReturnType()) << ' ';
1022 if (!F->getName().empty())
1023 Out << getLLVMName(F->getName());
1027 Machine.incorporateFunction(F);
1029 // Loop over the arguments, printing them...
1030 const FunctionType *FT = F->getFunctionType();
1032 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1036 // Finish printing arguments...
1037 if (FT->isVarArg()) {
1038 if (FT->getNumParams()) Out << ", ";
1039 Out << "..."; // Output varargs portion of signature!
1043 if (F->hasSection())
1044 Out << " section \"" << F->getSection() << '"';
1045 if (F->getAlignment())
1046 Out << " align " << F->getAlignment();
1048 if (F->isExternal()) {
1053 // Output all of its basic blocks... for the function
1054 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1060 Machine.purgeFunction();
1063 /// printArgument - This member is called for every argument that is passed into
1064 /// the function. Simply print it out
1066 void AssemblyWriter::printArgument(const Argument *Arg) {
1067 // Insert commas as we go... the first arg doesn't get a comma
1068 if (Arg != Arg->getParent()->arg_begin()) Out << ", ";
1071 printType(Arg->getType());
1073 // Output name, if available...
1075 Out << ' ' << getLLVMName(Arg->getName());
1078 /// printBasicBlock - This member is called for each basic block in a method.
1080 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1081 if (BB->hasName()) { // Print out the label if it exists...
1082 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1083 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1084 Out << "\n; <label>:";
1085 int Slot = Machine.getSlot(BB);
1092 if (BB->getParent() == 0)
1093 Out << "\t\t; Error: Block without parent!";
1095 if (BB != &BB->getParent()->front()) { // Not the entry block?
1096 // Output predecessors for the block...
1098 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1101 Out << " No predecessors!";
1104 writeOperand(*PI, false, true);
1105 for (++PI; PI != PE; ++PI) {
1107 writeOperand(*PI, false, true);
1115 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1117 // Output all of the instructions in the basic block...
1118 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1119 printInstruction(*I);
1121 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1125 /// printInfoComment - Print a little comment after the instruction indicating
1126 /// which slot it occupies.
1128 void AssemblyWriter::printInfoComment(const Value &V) {
1129 if (V.getType() != Type::VoidTy) {
1131 printType(V.getType()) << '>';
1134 int SlotNum = Machine.getSlot(&V);
1138 Out << ':' << SlotNum; // Print out the def slot taken.
1140 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1144 // This member is called for each Instruction in a function..
1145 void AssemblyWriter::printInstruction(const Instruction &I) {
1146 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1150 // Print out name if it exists...
1152 Out << getLLVMName(I.getName()) << " = ";
1154 // If this is a volatile load or store, print out the volatile marker.
1155 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1156 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1158 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1159 // If this is a call, check if it's a tail call.
1163 // Print out the opcode...
1164 Out << I.getOpcodeName();
1166 // Print out the compare instruction predicates
1167 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1168 Out << " " << getPredicateText(FCI->getPredicate());
1169 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1170 Out << " " << getPredicateText(ICI->getPredicate());
1173 // Print out the type of the operands...
1174 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1176 // Special case conditional branches to swizzle the condition out to the front
1177 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1178 writeOperand(I.getOperand(2), true);
1180 writeOperand(Operand, true);
1182 writeOperand(I.getOperand(1), true);
1184 } else if (isa<SwitchInst>(I)) {
1185 // Special case switch statement to get formatting nice and correct...
1186 writeOperand(Operand , true); Out << ',';
1187 writeOperand(I.getOperand(1), true); Out << " [";
1189 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1191 writeOperand(I.getOperand(op ), true); Out << ',';
1192 writeOperand(I.getOperand(op+1), true);
1195 } else if (isa<PHINode>(I)) {
1197 printType(I.getType());
1200 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1201 if (op) Out << ", ";
1203 writeOperand(I.getOperand(op ), false); Out << ',';
1204 writeOperand(I.getOperand(op+1), false); Out << " ]";
1206 } else if (isa<ReturnInst>(I) && !Operand) {
1208 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1209 // Print the calling convention being used.
1210 switch (CI->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" << CI->getCallingConv(); break;
1220 const PointerType *PTy = cast<PointerType>(Operand->getType());
1221 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1222 const Type *RetTy = FTy->getReturnType();
1224 // If possible, print out the short form of the call instruction. We can
1225 // only do this if the first argument is a pointer to a nonvararg function,
1226 // and if the return type is not a pointer to a function.
1228 if (!FTy->isVarArg() &&
1229 (!isa<PointerType>(RetTy) ||
1230 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1231 Out << ' '; printType(RetTy);
1232 writeOperand(Operand, false);
1234 writeOperand(Operand, true);
1237 if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true);
1238 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
1240 writeOperand(I.getOperand(op), true);
1244 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1245 const PointerType *PTy = cast<PointerType>(Operand->getType());
1246 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1247 const Type *RetTy = FTy->getReturnType();
1249 // Print the calling convention being used.
1250 switch (II->getCallingConv()) {
1251 case CallingConv::C: break; // default
1252 case CallingConv::CSRet: Out << " csretcc"; break;
1253 case CallingConv::Fast: Out << " fastcc"; break;
1254 case CallingConv::Cold: Out << " coldcc"; break;
1255 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1256 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1257 default: Out << " cc" << II->getCallingConv(); break;
1260 // If possible, print out the short form of the invoke instruction. We can
1261 // only do this if the first argument is a pointer to a nonvararg function,
1262 // and if the return type is not a pointer to a function.
1264 if (!FTy->isVarArg() &&
1265 (!isa<PointerType>(RetTy) ||
1266 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1267 Out << ' '; printType(RetTy);
1268 writeOperand(Operand, false);
1270 writeOperand(Operand, true);
1274 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1275 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1277 writeOperand(I.getOperand(op), true);
1280 Out << " )\n\t\t\tto";
1281 writeOperand(II->getNormalDest(), true);
1283 writeOperand(II->getUnwindDest(), true);
1285 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1287 printType(AI->getType()->getElementType());
1288 if (AI->isArrayAllocation()) {
1290 writeOperand(AI->getArraySize(), true);
1292 if (AI->getAlignment()) {
1293 Out << ", align " << AI->getAlignment();
1295 } else if (isa<CastInst>(I)) {
1296 if (Operand) writeOperand(Operand, true); // Work with broken code
1298 printType(I.getType());
1299 } else if (isa<VAArgInst>(I)) {
1300 if (Operand) writeOperand(Operand, true); // Work with broken code
1302 printType(I.getType());
1303 } else if (Operand) { // Print the normal way...
1305 // PrintAllTypes - Instructions who have operands of all the same type
1306 // omit the type from all but the first operand. If the instruction has
1307 // different type operands (for example br), then they are all printed.
1308 bool PrintAllTypes = false;
1309 const Type *TheType = Operand->getType();
1311 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1312 // types even if all operands are bools.
1313 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1314 isa<ShuffleVectorInst>(I)) {
1315 PrintAllTypes = true;
1317 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1318 Operand = I.getOperand(i);
1319 if (Operand->getType() != TheType) {
1320 PrintAllTypes = true; // We have differing types! Print them all!
1326 if (!PrintAllTypes) {
1331 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1333 writeOperand(I.getOperand(i), PrintAllTypes);
1337 printInfoComment(I);
1342 //===----------------------------------------------------------------------===//
1343 // External Interface declarations
1344 //===----------------------------------------------------------------------===//
1346 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1347 SlotMachine SlotTable(this);
1348 AssemblyWriter W(o, SlotTable, this, AAW);
1352 void GlobalVariable::print(std::ostream &o) const {
1353 SlotMachine SlotTable(getParent());
1354 AssemblyWriter W(o, SlotTable, getParent(), 0);
1358 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1359 SlotMachine SlotTable(getParent());
1360 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1365 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1366 WriteAsOperand(o, this, true, true, 0);
1369 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1370 SlotMachine SlotTable(getParent());
1371 AssemblyWriter W(o, SlotTable,
1372 getParent() ? getParent()->getParent() : 0, AAW);
1376 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1377 const Function *F = getParent() ? getParent()->getParent() : 0;
1378 SlotMachine SlotTable(F);
1379 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1384 void Constant::print(std::ostream &o) const {
1385 if (this == 0) { o << "<null> constant value\n"; return; }
1387 o << ' ' << getType()->getDescription() << ' ';
1389 std::map<const Type *, std::string> TypeTable;
1390 WriteConstantInt(o, this, false, TypeTable, 0);
1393 void Type::print(std::ostream &o) const {
1397 o << getDescription();
1400 void Argument::print(std::ostream &o) const {
1401 WriteAsOperand(o, this, true, true,
1402 getParent() ? getParent()->getParent() : 0);
1405 // Value::dump - allow easy printing of Values from the debugger.
1406 // Located here because so much of the needed functionality is here.
1407 void Value::dump() const { print(std::cerr); llvm_cerr << '\n'; }
1409 // Type::dump - allow easy printing of Values from the debugger.
1410 // Located here because so much of the needed functionality is here.
1411 void Type::dump() const { print(std::cerr); llvm_cerr << '\n'; }
1413 //===----------------------------------------------------------------------===//
1414 // CachedWriter Class Implementation
1415 //===----------------------------------------------------------------------===//
1417 void CachedWriter::setModule(const Module *M) {
1418 delete SC; delete AW;
1420 SC = new SlotMachine(M );
1421 AW = new AssemblyWriter(Out, *SC, M, 0);
1427 CachedWriter::~CachedWriter() {
1432 CachedWriter &CachedWriter::operator<<(const Value &V) {
1433 assert(AW && SC && "CachedWriter does not have a current module!");
1434 if (const Instruction *I = dyn_cast<Instruction>(&V))
1436 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(&V))
1438 else if (const Function *F = dyn_cast<Function>(&V))
1440 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(&V))
1443 AW->writeOperand(&V, true, true);
1447 CachedWriter& CachedWriter::operator<<(const Type &Ty) {
1448 if (SymbolicTypes) {
1449 const Module *M = AW->getModule();
1450 if (M) WriteTypeSymbolic(Out, &Ty, M);
1457 //===----------------------------------------------------------------------===//
1458 //===-- SlotMachine Implementation
1459 //===----------------------------------------------------------------------===//
1462 #define SC_DEBUG(X) llvm_cerr << X
1467 // Module level constructor. Causes the contents of the Module (sans functions)
1468 // to be added to the slot table.
1469 SlotMachine::SlotMachine(const Module *M)
1470 : TheModule(M) ///< Saved for lazy initialization.
1472 , FunctionProcessed(false)
1480 // Function level constructor. Causes the contents of the Module and the one
1481 // function provided to be added to the slot table.
1482 SlotMachine::SlotMachine(const Function *F )
1483 : TheModule( F ? F->getParent() : 0 ) ///< Saved for lazy initialization
1484 , TheFunction(F) ///< Saved for lazy initialization
1485 , FunctionProcessed(false)
1493 inline void SlotMachine::initialize(void) {
1496 TheModule = 0; ///< Prevent re-processing next time we're called.
1498 if ( TheFunction && ! FunctionProcessed) {
1503 // Iterate through all the global variables, functions, and global
1504 // variable initializers and create slots for them.
1505 void SlotMachine::processModule() {
1506 SC_DEBUG("begin processModule!\n");
1508 // Add all of the global variables to the value table...
1509 for (Module::const_global_iterator I = TheModule->global_begin(),
1510 E = TheModule->global_end(); I != E; ++I)
1513 // Add all the functions to the table
1514 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1518 SC_DEBUG("end processModule!\n");
1522 // Process the arguments, basic blocks, and instructions of a function.
1523 void SlotMachine::processFunction() {
1524 SC_DEBUG("begin processFunction!\n");
1526 // Add all the function arguments
1527 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1528 AE = TheFunction->arg_end(); AI != AE; ++AI)
1531 SC_DEBUG("Inserting Instructions:\n");
1533 // Add all of the basic blocks and instructions
1534 for (Function::const_iterator BB = TheFunction->begin(),
1535 E = TheFunction->end(); BB != E; ++BB) {
1537 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1542 FunctionProcessed = true;
1544 SC_DEBUG("end processFunction!\n");
1547 // Clean up after incorporating a function. This is the only way
1548 // to get out of the function incorporation state that affects the
1549 // getSlot/createSlot lock. Function incorporation state is indicated
1550 // by TheFunction != 0.
1551 void SlotMachine::purgeFunction() {
1552 SC_DEBUG("begin purgeFunction!\n");
1553 fMap.clear(); // Simply discard the function level map
1556 FunctionProcessed = false;
1557 SC_DEBUG("end purgeFunction!\n");
1560 /// Get the slot number for a value. This function will assert if you
1561 /// ask for a Value that hasn't previously been inserted with createSlot.
1562 /// Types are forbidden because Type does not inherit from Value (any more).
1563 int SlotMachine::getSlot(const Value *V) {
1564 assert( V && "Can't get slot for null Value" );
1565 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1566 "Can't insert a non-GlobalValue Constant into SlotMachine");
1568 // Check for uninitialized state and do lazy initialization
1571 // Get the type of the value
1572 const Type* VTy = V->getType();
1574 // Find the type plane in the module map
1575 TypedPlanes::const_iterator MI = mMap.find(VTy);
1577 if ( TheFunction ) {
1578 // Lookup the type in the function map too
1579 TypedPlanes::const_iterator FI = fMap.find(VTy);
1580 // If there is a corresponding type plane in the function map
1581 if ( FI != fMap.end() ) {
1582 // Lookup the Value in the function map
1583 ValueMap::const_iterator FVI = FI->second.map.find(V);
1584 // If the value doesn't exist in the function map
1585 if ( FVI == FI->second.map.end() ) {
1586 // Look up the value in the module map.
1587 if (MI == mMap.end()) return -1;
1588 ValueMap::const_iterator MVI = MI->second.map.find(V);
1589 // If we didn't find it, it wasn't inserted
1590 if (MVI == MI->second.map.end()) return -1;
1591 assert( MVI != MI->second.map.end() && "Value not found");
1592 // We found it only at the module level
1595 // else the value exists in the function map
1597 // Return the slot number as the module's contribution to
1598 // the type plane plus the index in the function's contribution
1599 // to the type plane.
1600 if (MI != mMap.end())
1601 return MI->second.next_slot + FVI->second;
1608 // N.B. Can get here only if either !TheFunction or the function doesn't
1609 // have a corresponding type plane for the Value
1611 // Make sure the type plane exists
1612 if (MI == mMap.end()) return -1;
1613 // Lookup the value in the module's map
1614 ValueMap::const_iterator MVI = MI->second.map.find(V);
1615 // Make sure we found it.
1616 if (MVI == MI->second.map.end()) return -1;
1621 /// Get the slot number for a value. This function will assert if you
1622 /// ask for a Value that hasn't previously been inserted with createSlot.
1623 /// Types are forbidden because Type does not inherit from Value (any more).
1624 int SlotMachine::getSlot(const Type *Ty) {
1625 assert( Ty && "Can't get slot for null Type" );
1627 // Check for uninitialized state and do lazy initialization
1630 if ( TheFunction ) {
1631 // Lookup the Type in the function map
1632 TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1633 // If the Type doesn't exist in the function map
1634 if ( FTI == fTypes.map.end() ) {
1635 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1636 // If we didn't find it, it wasn't inserted
1637 if (MTI == mTypes.map.end())
1639 // We found it only at the module level
1642 // else the value exists in the function map
1644 // Return the slot number as the module's contribution to
1645 // the type plane plus the index in the function's contribution
1646 // to the type plane.
1647 return mTypes.next_slot + FTI->second;
1651 // N.B. Can get here only if either !TheFunction
1653 // Lookup the value in the module's map
1654 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1655 // Make sure we found it.
1656 if (MTI == mTypes.map.end()) return -1;
1661 // Create a new slot, or return the existing slot if it is already
1662 // inserted. Note that the logic here parallels getSlot but instead
1663 // of asserting when the Value* isn't found, it inserts the value.
1664 unsigned SlotMachine::createSlot(const Value *V) {
1665 assert( V && "Can't insert a null Value to SlotMachine");
1666 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1667 "Can't insert a non-GlobalValue Constant into SlotMachine");
1669 const Type* VTy = V->getType();
1671 // Just ignore void typed things
1672 if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value!
1674 // Look up the type plane for the Value's type from the module map
1675 TypedPlanes::const_iterator MI = mMap.find(VTy);
1677 if ( TheFunction ) {
1678 // Get the type plane for the Value's type from the function map
1679 TypedPlanes::const_iterator FI = fMap.find(VTy);
1680 // If there is a corresponding type plane in the function map
1681 if ( FI != fMap.end() ) {
1682 // Lookup the Value in the function map
1683 ValueMap::const_iterator FVI = FI->second.map.find(V);
1684 // If the value doesn't exist in the function map
1685 if ( FVI == FI->second.map.end() ) {
1686 // If there is no corresponding type plane in the module map
1687 if ( MI == mMap.end() )
1688 return insertValue(V);
1689 // Look up the value in the module map
1690 ValueMap::const_iterator MVI = MI->second.map.find(V);
1691 // If we didn't find it, it wasn't inserted
1692 if ( MVI == MI->second.map.end() )
1693 return insertValue(V);
1695 // We found it only at the module level
1698 // else the value exists in the function map
1700 if ( MI == mMap.end() )
1703 // Return the slot number as the module's contribution to
1704 // the type plane plus the index in the function's contribution
1705 // to the type plane.
1706 return MI->second.next_slot + FVI->second;
1709 // else there is not a corresponding type plane in the function map
1711 // If the type plane doesn't exists at the module level
1712 if ( MI == mMap.end() ) {
1713 return insertValue(V);
1714 // else type plane exists at the module level, examine it
1716 // Look up the value in the module's map
1717 ValueMap::const_iterator MVI = MI->second.map.find(V);
1718 // If we didn't find it there either
1719 if ( MVI == MI->second.map.end() )
1720 // Return the slot number as the module's contribution to
1721 // the type plane plus the index of the function map insertion.
1722 return MI->second.next_slot + insertValue(V);
1729 // N.B. Can only get here if !TheFunction
1731 // If the module map's type plane is not for the Value's type
1732 if ( MI != mMap.end() ) {
1733 // Lookup the value in the module's map
1734 ValueMap::const_iterator MVI = MI->second.map.find(V);
1735 if ( MVI != MI->second.map.end() )
1739 return insertValue(V);
1742 // Create a new slot, or return the existing slot if it is already
1743 // inserted. Note that the logic here parallels getSlot but instead
1744 // of asserting when the Value* isn't found, it inserts the value.
1745 unsigned SlotMachine::createSlot(const Type *Ty) {
1746 assert( Ty && "Can't insert a null Type to SlotMachine");
1748 if ( TheFunction ) {
1749 // Lookup the Type in the function map
1750 TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1751 // If the type doesn't exist in the function map
1752 if ( FTI == fTypes.map.end() ) {
1753 // Look up the type in the module map
1754 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1755 // If we didn't find it, it wasn't inserted
1756 if ( MTI == mTypes.map.end() )
1757 return insertValue(Ty);
1759 // We found it only at the module level
1762 // else the value exists in the function map
1764 // Return the slot number as the module's contribution to
1765 // the type plane plus the index in the function's contribution
1766 // to the type plane.
1767 return mTypes.next_slot + FTI->second;
1771 // N.B. Can only get here if !TheFunction
1773 // Lookup the type in the module's map
1774 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1775 if ( MTI != mTypes.map.end() )
1778 return insertValue(Ty);
1781 // Low level insert function. Minimal checking is done. This
1782 // function is just for the convenience of createSlot (above).
1783 unsigned SlotMachine::insertValue(const Value *V ) {
1784 assert(V && "Can't insert a null Value into SlotMachine!");
1785 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1786 "Can't insert a non-GlobalValue Constant into SlotMachine");
1788 // If this value does not contribute to a plane (is void)
1789 // or if the value already has a name then ignore it.
1790 if (V->getType() == Type::VoidTy || V->hasName() ) {
1791 SC_DEBUG("ignored value " << *V << "\n");
1792 return 0; // FIXME: Wrong return value
1795 const Type *VTy = V->getType();
1796 unsigned DestSlot = 0;
1798 if ( TheFunction ) {
1799 TypedPlanes::iterator I = fMap.find( VTy );
1800 if ( I == fMap.end() )
1801 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1802 DestSlot = I->second.map[V] = I->second.next_slot++;
1804 TypedPlanes::iterator I = mMap.find( VTy );
1805 if ( I == mMap.end() )
1806 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1807 DestSlot = I->second.map[V] = I->second.next_slot++;
1810 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1812 // G = Global, C = Constant, T = Type, F = Function, o = other
1813 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' :
1814 (isa<Constant>(V) ? 'C' : 'o'))));
1819 // Low level insert function. Minimal checking is done. This
1820 // function is just for the convenience of createSlot (above).
1821 unsigned SlotMachine::insertValue(const Type *Ty ) {
1822 assert(Ty && "Can't insert a null Type into SlotMachine!");
1824 unsigned DestSlot = 0;
1826 if ( TheFunction ) {
1827 DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
1829 DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
1831 SC_DEBUG(" Inserting type [" << DestSlot << "] = " << Ty << "\n");