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/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/SymbolTable.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/Support/CFG.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/STLExtras.h"
37 // Make virtual table appear in this compilation unit.
38 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
40 /// This class provides computation of slot numbers for LLVM Assembly writing.
41 /// @brief LLVM Assembly Writing Slot Computation.
48 /// @brief A mapping of Values to slot numbers
49 typedef std::map<const Value*, unsigned> ValueMap;
50 typedef std::map<const Type*, unsigned> TypeMap;
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
62 TypePlane() { next_slot = 0; }
63 void clear() { map.clear(); next_slot = 0; }
66 /// @brief The map of planes by Type
67 typedef std::map<const Type*, ValuePlane> TypedPlanes;
70 /// @name Constructors
73 /// @brief Construct from a module
74 SlotMachine(const Module *M );
76 /// @brief Construct from a function, starting out in incorp state.
77 SlotMachine(const Function *F );
83 /// Return the slot number of the specified value in it's type
84 /// plane. Its an error to ask for something not in the SlotMachine.
85 /// Its an error to ask for a Type*
86 int getSlot(const Value *V);
87 int getSlot(const Type*Ty);
89 /// Determine if a Value has a slot or not
90 bool hasSlot(const Value* V);
91 bool hasSlot(const Type* Ty);
97 /// If you'd like to deal with a function instead of just a module, use
98 /// this method to get its data into the SlotMachine.
99 void incorporateFunction(const Function *F) {
101 FunctionProcessed = false;
104 /// After calling incorporateFunction, use this method to remove the
105 /// most recently incorporated function from the SlotMachine. This
106 /// will reset the state of the machine back to just the module contents.
107 void purgeFunction();
110 /// @name Implementation Details
113 /// This function does the actual initialization.
114 inline void initialize();
116 /// Values can be crammed into here at will. If they haven't
117 /// been inserted already, they get inserted, otherwise they are ignored.
118 /// Either way, the slot number for the Value* is returned.
119 unsigned createSlot(const Value *V);
120 unsigned createSlot(const Type* Ty);
122 /// Insert a value into the value table. Return the slot number
123 /// that it now occupies. BadThings(TM) will happen if you insert a
124 /// Value that's already been inserted.
125 unsigned insertValue( const Value *V );
126 unsigned insertValue( const Type* Ty);
128 /// Add all of the module level global variables (and their initializers)
129 /// and function declarations, but not the contents of those functions.
130 void processModule();
132 /// Add all of the functions arguments, basic blocks, and instructions
133 void processFunction();
135 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
136 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
143 /// @brief The module for which we are holding slot numbers
144 const Module* TheModule;
146 /// @brief The function for which we are holding slot numbers
147 const Function* TheFunction;
148 bool FunctionProcessed;
150 /// @brief The TypePlanes map for the module level data
154 /// @brief The TypePlanes map for the function level data
162 } // end namespace llvm
164 static RegisterPass<PrintModulePass>
165 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
166 static RegisterPass<PrintFunctionPass>
167 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
169 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
171 std::map<const Type *, std::string> &TypeTable,
172 SlotMachine *Machine);
174 static void WriteAsOperandInternal(std::ostream &Out, const Type *T,
176 std::map<const Type *, std::string> &TypeTable,
177 SlotMachine *Machine);
179 static const Module *getModuleFromVal(const Value *V) {
180 if (const Argument *MA = dyn_cast<Argument>(V))
181 return MA->getParent() ? MA->getParent()->getParent() : 0;
182 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
183 return BB->getParent() ? BB->getParent()->getParent() : 0;
184 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
185 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
186 return M ? M->getParent() : 0;
187 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
188 return GV->getParent();
192 static SlotMachine *createSlotMachine(const Value *V) {
193 if (const Argument *FA = dyn_cast<Argument>(V)) {
194 return new SlotMachine(FA->getParent());
195 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
196 return new SlotMachine(I->getParent()->getParent());
197 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
198 return new SlotMachine(BB->getParent());
199 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
200 return new SlotMachine(GV->getParent());
201 } else if (const Function *Func = dyn_cast<Function>(V)) {
202 return new SlotMachine(Func);
207 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
208 // prefixed with % (if the string only contains simple characters) or is
209 // surrounded with ""'s (if it has special chars in it).
210 static std::string getLLVMName(const std::string &Name,
211 bool prefixName = true) {
212 assert(!Name.empty() && "Cannot get empty name!");
214 // First character cannot start with a number...
215 if (Name[0] >= '0' && Name[0] <= '9')
216 return "\"" + Name + "\"";
218 // Scan to see if we have any characters that are not on the "white list"
219 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
221 assert(C != '"' && "Illegal character in LLVM value name!");
222 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
223 C != '-' && C != '.' && C != '_')
224 return "\"" + Name + "\"";
227 // If we get here, then the identifier is legal to use as a "VarID".
235 /// fillTypeNameTable - If the module has a symbol table, take all global types
236 /// and stuff their names into the TypeNames map.
238 static void fillTypeNameTable(const Module *M,
239 std::map<const Type *, std::string> &TypeNames) {
241 const SymbolTable &ST = M->getSymbolTable();
242 SymbolTable::type_const_iterator TI = ST.type_begin();
243 for (; TI != ST.type_end(); ++TI ) {
244 // As a heuristic, don't insert pointer to primitive types, because
245 // they are used too often to have a single useful name.
247 const Type *Ty = cast<Type>(TI->second);
248 if (!isa<PointerType>(Ty) ||
249 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
250 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
251 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
257 static void calcTypeName(const Type *Ty,
258 std::vector<const Type *> &TypeStack,
259 std::map<const Type *, std::string> &TypeNames,
260 std::string & Result){
261 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
262 Result += Ty->getDescription(); // Base case
266 // Check to see if the type is named.
267 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
268 if (I != TypeNames.end()) {
273 if (isa<OpaqueType>(Ty)) {
278 // Check to see if the Type is already on the stack...
279 unsigned Slot = 0, CurSize = TypeStack.size();
280 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
282 // This is another base case for the recursion. In this case, we know
283 // that we have looped back to a type that we have previously visited.
284 // Generate the appropriate upreference to handle this.
285 if (Slot < CurSize) {
286 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
290 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
292 switch (Ty->getTypeID()) {
293 case Type::FunctionTyID: {
294 const FunctionType *FTy = cast<FunctionType>(Ty);
295 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
297 for (FunctionType::param_iterator I = FTy->param_begin(),
298 E = FTy->param_end(); I != E; ++I) {
299 if (I != FTy->param_begin())
301 calcTypeName(*I, TypeStack, TypeNames, Result);
303 if (FTy->isVarArg()) {
304 if (FTy->getNumParams()) Result += ", ";
310 case Type::StructTyID: {
311 const StructType *STy = cast<StructType>(Ty);
313 for (StructType::element_iterator I = STy->element_begin(),
314 E = STy->element_end(); I != E; ++I) {
315 if (I != STy->element_begin())
317 calcTypeName(*I, TypeStack, TypeNames, Result);
322 case Type::PointerTyID:
323 calcTypeName(cast<PointerType>(Ty)->getElementType(),
324 TypeStack, TypeNames, Result);
327 case Type::ArrayTyID: {
328 const ArrayType *ATy = cast<ArrayType>(Ty);
329 Result += "[" + utostr(ATy->getNumElements()) + " x ";
330 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
334 case Type::PackedTyID: {
335 const PackedType *PTy = cast<PackedType>(Ty);
336 Result += "<" + utostr(PTy->getNumElements()) + " x ";
337 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
341 case Type::OpaqueTyID:
345 Result += "<unrecognized-type>";
348 TypeStack.pop_back(); // Remove self from stack...
353 /// printTypeInt - The internal guts of printing out a type that has a
354 /// potentially named portion.
356 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
357 std::map<const Type *, std::string> &TypeNames) {
358 // Primitive types always print out their description, regardless of whether
359 // they have been named or not.
361 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
362 return Out << Ty->getDescription();
364 // Check to see if the type is named.
365 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
366 if (I != TypeNames.end()) return Out << I->second;
368 // Otherwise we have a type that has not been named but is a derived type.
369 // Carefully recurse the type hierarchy to print out any contained symbolic
372 std::vector<const Type *> TypeStack;
373 std::string TypeName;
374 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
375 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
376 return (Out << TypeName);
380 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
381 /// type, iff there is an entry in the modules symbol table for the specified
382 /// type or one of it's component types. This is slower than a simple x << Type
384 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
388 // If they want us to print out a type, attempt to make it symbolic if there
389 // is a symbol table in the module...
391 std::map<const Type *, std::string> TypeNames;
392 fillTypeNameTable(M, TypeNames);
394 return printTypeInt(Out, Ty, TypeNames);
396 return Out << Ty->getDescription();
400 /// @brief Internal constant writer.
401 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
403 std::map<const Type *, std::string> &TypeTable,
404 SlotMachine *Machine) {
405 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
406 Out << (CB == ConstantBool::True ? "true" : "false");
407 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
408 Out << CI->getValue();
409 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
410 Out << CI->getValue();
411 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
412 // We would like to output the FP constant value in exponential notation,
413 // but we cannot do this if doing so will lose precision. Check here to
414 // make sure that we only output it in exponential format if we can parse
415 // the value back and get the same value.
417 std::string StrVal = ftostr(CFP->getValue());
419 // Check to make sure that the stringized number is not some string like
420 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
421 // the string matches the "[-+]?[0-9]" regex.
423 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
424 ((StrVal[0] == '-' || StrVal[0] == '+') &&
425 (StrVal[1] >= '0' && StrVal[1] <= '9')))
426 // Reparse stringized version!
427 if (atof(StrVal.c_str()) == CFP->getValue()) {
432 // Otherwise we could not reparse it to exactly the same value, so we must
433 // output the string in hexadecimal format!
435 // Behave nicely in the face of C TBAA rules... see:
436 // http://www.nullstone.com/htmls/category/aliastyp.htm
442 V.D = CFP->getValue();
443 assert(sizeof(double) == sizeof(uint64_t) &&
444 "assuming that double is 64 bits!");
445 Out << "0x" << utohexstr(V.U);
447 } else if (isa<ConstantAggregateZero>(CV)) {
448 Out << "zeroinitializer";
449 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
450 // As a special case, print the array as a string if it is an array of
451 // ubytes or an array of sbytes with positive values.
453 const Type *ETy = CA->getType()->getElementType();
454 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
456 if (ETy == Type::SByteTy)
457 for (unsigned i = 0; i < CA->getNumOperands(); ++i)
458 if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
465 for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
467 (unsigned char)cast<ConstantInt>(CA->getOperand(i))->getRawValue();
469 if (isprint(C) && C != '"' && C != '\\') {
473 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
474 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
479 } else { // Cannot output in string format...
481 if (CA->getNumOperands()) {
483 printTypeInt(Out, ETy, TypeTable);
484 WriteAsOperandInternal(Out, CA->getOperand(0),
485 PrintName, TypeTable, Machine);
486 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
488 printTypeInt(Out, ETy, TypeTable);
489 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
495 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
497 if (CS->getNumOperands()) {
499 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
501 WriteAsOperandInternal(Out, CS->getOperand(0),
502 PrintName, TypeTable, Machine);
504 for (unsigned i = 1; i < CS->getNumOperands(); i++) {
506 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
508 WriteAsOperandInternal(Out, CS->getOperand(i),
509 PrintName, TypeTable, Machine);
514 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
515 const Type *ETy = CP->getType()->getElementType();
516 assert(CP->getNumOperands() > 0 &&
517 "Number of operands for a PackedConst must be > 0");
520 printTypeInt(Out, ETy, TypeTable);
521 WriteAsOperandInternal(Out, CP->getOperand(0),
522 PrintName, TypeTable, Machine);
523 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
525 printTypeInt(Out, ETy, TypeTable);
526 WriteAsOperandInternal(Out, CP->getOperand(i), PrintName,
530 } else if (isa<ConstantPointerNull>(CV)) {
533 } else if (isa<UndefValue>(CV)) {
536 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
537 Out << CE->getOpcodeName() << " (";
539 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
540 printTypeInt(Out, (*OI)->getType(), TypeTable);
541 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
542 if (OI+1 != CE->op_end())
546 if (CE->getOpcode() == Instruction::Cast) {
548 printTypeInt(Out, CE->getType(), TypeTable);
553 Out << "<placeholder or erroneous Constant>";
558 /// WriteAsOperand - Write the name of the specified value out to the specified
559 /// ostream. This can be useful when you just want to print int %reg126, not
560 /// the whole instruction that generated it.
562 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
564 std::map<const Type*, std::string> &TypeTable,
565 SlotMachine *Machine) {
567 if ((PrintName || isa<GlobalValue>(V)) && V->hasName())
568 Out << getLLVMName(V->getName());
570 const Constant *CV = dyn_cast<Constant>(V);
571 if (CV && !isa<GlobalValue>(CV))
572 WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
576 Slot = Machine->getSlot(V);
578 Machine = createSlotMachine(V);
580 Slot = Machine->getSlot(V);
593 /// WriteAsOperand - Write the name of the specified value out to the specified
594 /// ostream. This can be useful when you just want to print int %reg126, not
595 /// the whole instruction that generated it.
597 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
598 bool PrintType, bool PrintName,
599 const Module *Context) {
600 std::map<const Type *, std::string> TypeNames;
601 if (Context == 0) Context = getModuleFromVal(V);
604 fillTypeNameTable(Context, TypeNames);
607 printTypeInt(Out, V->getType(), TypeNames);
609 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
613 /// WriteAsOperandInternal - Write the name of the specified value out to
614 /// the specified ostream. This can be useful when you just want to print
615 /// int %reg126, not the whole instruction that generated it.
617 static void WriteAsOperandInternal(std::ostream &Out, const Type *T,
619 std::map<const Type*, std::string> &TypeTable,
620 SlotMachine *Machine) {
624 Slot = Machine->getSlot(T);
630 Out << T->getDescription();
634 /// WriteAsOperand - Write the name of the specified value out to the specified
635 /// ostream. This can be useful when you just want to print int %reg126, not
636 /// the whole instruction that generated it.
638 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Type *Ty,
639 bool PrintType, bool PrintName,
640 const Module *Context) {
641 std::map<const Type *, std::string> TypeNames;
642 assert(Context != 0 && "Can't write types as operand without module context");
644 fillTypeNameTable(Context, TypeNames);
647 // printTypeInt(Out, V->getType(), TypeNames);
649 printTypeInt(Out, Ty, TypeNames);
651 WriteAsOperandInternal(Out, Ty, PrintName, TypeNames, 0);
657 class AssemblyWriter {
659 SlotMachine &Machine;
660 const Module *TheModule;
661 std::map<const Type *, std::string> TypeNames;
662 AssemblyAnnotationWriter *AnnotationWriter;
664 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
665 AssemblyAnnotationWriter *AAW)
666 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
668 // If the module has a symbol table, take all global types and stuff their
669 // names into the TypeNames map.
671 fillTypeNameTable(M, TypeNames);
674 inline void write(const Module *M) { printModule(M); }
675 inline void write(const GlobalVariable *G) { printGlobal(G); }
676 inline void write(const Function *F) { printFunction(F); }
677 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
678 inline void write(const Instruction *I) { printInstruction(*I); }
679 inline void write(const Constant *CPV) { printConstant(CPV); }
680 inline void write(const Type *Ty) { printType(Ty); }
682 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
684 const Module* getModule() { return TheModule; }
687 void printModule(const Module *M);
688 void printSymbolTable(const SymbolTable &ST);
689 void printConstant(const Constant *CPV);
690 void printGlobal(const GlobalVariable *GV);
691 void printFunction(const Function *F);
692 void printArgument(const Argument *FA);
693 void printBasicBlock(const BasicBlock *BB);
694 void printInstruction(const Instruction &I);
696 // printType - Go to extreme measures to attempt to print out a short,
697 // symbolic version of a type name.
699 std::ostream &printType(const Type *Ty) {
700 return printTypeInt(Out, Ty, TypeNames);
703 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
704 // without considering any symbolic types that we may have equal to it.
706 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
708 // printInfoComment - Print a little comment after the instruction indicating
709 // which slot it occupies.
710 void printInfoComment(const Value &V);
712 } // end of llvm namespace
714 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
715 /// without considering any symbolic types that we may have equal to it.
717 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
718 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
719 printType(FTy->getReturnType()) << " (";
720 for (FunctionType::param_iterator I = FTy->param_begin(),
721 E = FTy->param_end(); I != E; ++I) {
722 if (I != FTy->param_begin())
726 if (FTy->isVarArg()) {
727 if (FTy->getNumParams()) Out << ", ";
731 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
733 for (StructType::element_iterator I = STy->element_begin(),
734 E = STy->element_end(); I != E; ++I) {
735 if (I != STy->element_begin())
740 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
741 printType(PTy->getElementType()) << '*';
742 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
743 Out << '[' << ATy->getNumElements() << " x ";
744 printType(ATy->getElementType()) << ']';
745 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
746 Out << '<' << PTy->getNumElements() << " x ";
747 printType(PTy->getElementType()) << '>';
749 else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
752 if (!Ty->isPrimitiveType())
753 Out << "<unknown derived type>";
760 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
763 if (PrintType) { Out << ' '; printType(Operand->getType()); }
764 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Machine);
766 Out << "<null operand!>";
771 void AssemblyWriter::printModule(const Module *M) {
772 if (!M->getModuleIdentifier().empty() &&
773 // Don't print the ID if it will start a new line (which would
774 // require a comment char before it).
775 M->getModuleIdentifier().find('\n') == std::string::npos)
776 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
778 switch (M->getEndianness()) {
779 case Module::LittleEndian: Out << "target endian = little\n"; break;
780 case Module::BigEndian: Out << "target endian = big\n"; break;
781 case Module::AnyEndianness: break;
783 switch (M->getPointerSize()) {
784 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
785 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
786 case Module::AnyPointerSize: break;
788 if (!M->getTargetTriple().empty())
789 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
791 // Loop over the dependent libraries and emit them.
792 Module::lib_iterator LI = M->lib_begin();
793 Module::lib_iterator LE = M->lib_end();
795 Out << "deplibs = [ ";
797 Out << '"' << *LI << '"';
805 // Loop over the symbol table, emitting all named constants.
806 printSymbolTable(M->getSymbolTable());
808 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I)
811 Out << "\nimplementation ; Functions:\n";
813 // Output all of the functions.
814 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
818 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
819 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
821 if (!GV->hasInitializer())
824 switch (GV->getLinkage()) {
825 case GlobalValue::InternalLinkage: Out << "internal "; break;
826 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
827 case GlobalValue::WeakLinkage: Out << "weak "; break;
828 case GlobalValue::AppendingLinkage: Out << "appending "; break;
829 case GlobalValue::ExternalLinkage: break;
830 case GlobalValue::GhostLinkage:
831 std::cerr << "GhostLinkage not allowed in AsmWriter!\n";
835 Out << (GV->isConstant() ? "constant " : "global ");
836 printType(GV->getType()->getElementType());
838 if (GV->hasInitializer()) {
839 Constant* C = cast<Constant>(GV->getInitializer());
840 assert(C && "GlobalVar initializer isn't constant?");
841 writeOperand(GV->getInitializer(), false, isa<GlobalValue>(C));
844 printInfoComment(*GV);
849 // printSymbolTable - Run through symbol table looking for constants
850 // and types. Emit their declarations.
851 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
854 for (SymbolTable::type_const_iterator TI = ST.type_begin();
855 TI != ST.type_end(); ++TI ) {
856 Out << "\t" << getLLVMName(TI->first) << " = type ";
858 // Make sure we print out at least one level of the type structure, so
859 // that we do not get %FILE = type %FILE
861 printTypeAtLeastOneLevel(TI->second) << "\n";
864 // Print the constants, in type plane order.
865 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
866 PI != ST.plane_end(); ++PI ) {
867 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
868 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
870 for (; VI != VE; ++VI) {
871 const Value* V = VI->second;
872 const Constant *CPV = dyn_cast<Constant>(V) ;
873 if (CPV && !isa<GlobalValue>(V)) {
881 /// printConstant - Print out a constant pool entry...
883 void AssemblyWriter::printConstant(const Constant *CPV) {
884 // Don't print out unnamed constants, they will be inlined
885 if (!CPV->hasName()) return;
888 Out << "\t" << getLLVMName(CPV->getName()) << " =";
890 // Write the value out now...
891 writeOperand(CPV, true, false);
893 printInfoComment(*CPV);
897 /// printFunction - Print all aspects of a function.
899 void AssemblyWriter::printFunction(const Function *F) {
900 // Print out the return type and name...
903 // Ensure that no local symbols conflict with global symbols.
904 const_cast<Function*>(F)->renameLocalSymbols();
906 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
911 switch (F->getLinkage()) {
912 case GlobalValue::InternalLinkage: Out << "internal "; break;
913 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
914 case GlobalValue::WeakLinkage: Out << "weak "; break;
915 case GlobalValue::AppendingLinkage: Out << "appending "; break;
916 case GlobalValue::ExternalLinkage: break;
917 case GlobalValue::GhostLinkage:
918 std::cerr << "GhostLinkage not allowed in AsmWriter!\n";
922 // Print the calling convention.
923 switch (F->getCallingConv()) {
924 case CallingConv::C: break; // default
925 case CallingConv::Fast: Out << "fastcc "; break;
926 case CallingConv::Cold: Out << "coldcc "; break;
927 default: Out << "cc" << F->getCallingConv() << " "; break;
930 printType(F->getReturnType()) << ' ';
931 if (!F->getName().empty())
932 Out << getLLVMName(F->getName());
936 Machine.incorporateFunction(F);
938 // Loop over the arguments, printing them...
939 const FunctionType *FT = F->getFunctionType();
941 for(Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
944 // Finish printing arguments...
945 if (FT->isVarArg()) {
946 if (FT->getNumParams()) Out << ", ";
947 Out << "..."; // Output varargs portion of signature!
951 if (F->isExternal()) {
956 // Output all of its basic blocks... for the function
957 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
963 Machine.purgeFunction();
966 /// printArgument - This member is called for every argument that is passed into
967 /// the function. Simply print it out
969 void AssemblyWriter::printArgument(const Argument *Arg) {
970 // Insert commas as we go... the first arg doesn't get a comma
971 if (Arg != Arg->getParent()->arg_begin()) Out << ", ";
974 printType(Arg->getType());
976 // Output name, if available...
978 Out << ' ' << getLLVMName(Arg->getName());
981 /// printBasicBlock - This member is called for each basic block in a method.
983 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
984 if (BB->hasName()) { // Print out the label if it exists...
985 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
986 } else if (!BB->use_empty()) { // Don't print block # of no uses...
987 Out << "\n; <label>:";
988 int Slot = Machine.getSlot(BB);
995 if (BB->getParent() == 0)
996 Out << "\t\t; Error: Block without parent!";
998 if (BB != &BB->getParent()->front()) { // Not the entry block?
999 // Output predecessors for the block...
1001 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1004 Out << " No predecessors!";
1007 writeOperand(*PI, false, true);
1008 for (++PI; PI != PE; ++PI) {
1010 writeOperand(*PI, false, true);
1018 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1020 // Output all of the instructions in the basic block...
1021 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1022 printInstruction(*I);
1024 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1028 /// printInfoComment - Print a little comment after the instruction indicating
1029 /// which slot it occupies.
1031 void AssemblyWriter::printInfoComment(const Value &V) {
1032 if (V.getType() != Type::VoidTy) {
1034 printType(V.getType()) << '>';
1037 int SlotNum = Machine.getSlot(&V);
1041 Out << ':' << SlotNum; // Print out the def slot taken.
1043 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1047 /// printInstruction - This member is called for each Instruction in a function..
1049 void AssemblyWriter::printInstruction(const Instruction &I) {
1050 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1054 // Print out name if it exists...
1056 Out << getLLVMName(I.getName()) << " = ";
1058 // If this is a volatile load or store, print out the volatile marker.
1059 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1060 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1062 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1063 // If this is a call, check if it's a tail call.
1067 // Print out the opcode...
1068 Out << I.getOpcodeName();
1070 // Print out the type of the operands...
1071 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1073 // Special case conditional branches to swizzle the condition out to the front
1074 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1075 writeOperand(I.getOperand(2), true);
1077 writeOperand(Operand, true);
1079 writeOperand(I.getOperand(1), true);
1081 } else if (isa<SwitchInst>(I)) {
1082 // Special case switch statement to get formatting nice and correct...
1083 writeOperand(Operand , true); Out << ',';
1084 writeOperand(I.getOperand(1), true); Out << " [";
1086 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1088 writeOperand(I.getOperand(op ), true); Out << ',';
1089 writeOperand(I.getOperand(op+1), true);
1092 } else if (isa<PHINode>(I)) {
1094 printType(I.getType());
1097 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1098 if (op) Out << ", ";
1100 writeOperand(I.getOperand(op ), false); Out << ',';
1101 writeOperand(I.getOperand(op+1), false); Out << " ]";
1103 } else if (isa<ReturnInst>(I) && !Operand) {
1105 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1106 // Print the calling convention being used.
1107 switch (CI->getCallingConv()) {
1108 case CallingConv::C: break; // default
1109 case CallingConv::Fast: Out << " fastcc"; break;
1110 case CallingConv::Cold: Out << " coldcc"; break;
1111 default: Out << " cc" << CI->getCallingConv(); break;
1114 const PointerType *PTy = cast<PointerType>(Operand->getType());
1115 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1116 const Type *RetTy = FTy->getReturnType();
1118 // If possible, print out the short form of the call instruction. We can
1119 // only do this if the first argument is a pointer to a nonvararg function,
1120 // and if the return type is not a pointer to a function.
1122 if (!FTy->isVarArg() &&
1123 (!isa<PointerType>(RetTy) ||
1124 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1125 Out << ' '; printType(RetTy);
1126 writeOperand(Operand, false);
1128 writeOperand(Operand, true);
1131 if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true);
1132 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
1134 writeOperand(I.getOperand(op), true);
1138 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1139 const PointerType *PTy = cast<PointerType>(Operand->getType());
1140 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1141 const Type *RetTy = FTy->getReturnType();
1143 // Print the calling convention being used.
1144 switch (II->getCallingConv()) {
1145 case CallingConv::C: break; // default
1146 case CallingConv::Fast: Out << " fastcc"; break;
1147 case CallingConv::Cold: Out << " coldcc"; break;
1148 default: Out << " cc" << II->getCallingConv(); break;
1151 // If possible, print out the short form of the invoke instruction. We can
1152 // only do this if the first argument is a pointer to a nonvararg function,
1153 // and if the return type is not a pointer to a function.
1155 if (!FTy->isVarArg() &&
1156 (!isa<PointerType>(RetTy) ||
1157 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1158 Out << ' '; printType(RetTy);
1159 writeOperand(Operand, false);
1161 writeOperand(Operand, true);
1165 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1166 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1168 writeOperand(I.getOperand(op), true);
1171 Out << " )\n\t\t\tto";
1172 writeOperand(II->getNormalDest(), true);
1174 writeOperand(II->getUnwindDest(), true);
1176 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1178 printType(AI->getType()->getElementType());
1179 if (AI->isArrayAllocation()) {
1181 writeOperand(AI->getArraySize(), true);
1183 } else if (isa<CastInst>(I)) {
1184 if (Operand) writeOperand(Operand, true); // Work with broken code
1186 printType(I.getType());
1187 } else if (isa<VAArgInst>(I)) {
1188 if (Operand) writeOperand(Operand, true); // Work with broken code
1190 printType(I.getType());
1191 } else if (Operand) { // Print the normal way...
1193 // PrintAllTypes - Instructions who have operands of all the same type
1194 // omit the type from all but the first operand. If the instruction has
1195 // different type operands (for example br), then they are all printed.
1196 bool PrintAllTypes = false;
1197 const Type *TheType = Operand->getType();
1199 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1200 // types even if all operands are bools.
1201 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I)) {
1202 PrintAllTypes = true;
1204 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1205 Operand = I.getOperand(i);
1206 if (Operand->getType() != TheType) {
1207 PrintAllTypes = true; // We have differing types! Print them all!
1213 if (!PrintAllTypes) {
1218 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1220 writeOperand(I.getOperand(i), PrintAllTypes);
1224 printInfoComment(I);
1229 //===----------------------------------------------------------------------===//
1230 // External Interface declarations
1231 //===----------------------------------------------------------------------===//
1233 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1234 SlotMachine SlotTable(this);
1235 AssemblyWriter W(o, SlotTable, this, AAW);
1239 void GlobalVariable::print(std::ostream &o) const {
1240 SlotMachine SlotTable(getParent());
1241 AssemblyWriter W(o, SlotTable, getParent(), 0);
1245 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1246 SlotMachine SlotTable(getParent());
1247 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1252 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1253 SlotMachine SlotTable(getParent());
1254 AssemblyWriter W(o, SlotTable,
1255 getParent() ? getParent()->getParent() : 0, AAW);
1259 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1260 const Function *F = getParent() ? getParent()->getParent() : 0;
1261 SlotMachine SlotTable(F);
1262 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1267 void Constant::print(std::ostream &o) const {
1268 if (this == 0) { o << "<null> constant value\n"; return; }
1270 o << ' ' << getType()->getDescription() << ' ';
1272 std::map<const Type *, std::string> TypeTable;
1273 WriteConstantInt(o, this, false, TypeTable, 0);
1276 void Type::print(std::ostream &o) const {
1280 o << getDescription();
1283 void Argument::print(std::ostream &o) const {
1284 WriteAsOperand(o, this, true, true,
1285 getParent() ? getParent()->getParent() : 0);
1288 // Value::dump - allow easy printing of Values from the debugger.
1289 // Located here because so much of the needed functionality is here.
1290 void Value::dump() const { print(std::cerr); }
1292 // Type::dump - allow easy printing of Values from the debugger.
1293 // Located here because so much of the needed functionality is here.
1294 void Type::dump() const { print(std::cerr); }
1296 //===----------------------------------------------------------------------===//
1297 // CachedWriter Class Implementation
1298 //===----------------------------------------------------------------------===//
1300 void CachedWriter::setModule(const Module *M) {
1301 delete SC; delete AW;
1303 SC = new SlotMachine(M );
1304 AW = new AssemblyWriter(Out, *SC, M, 0);
1310 CachedWriter::~CachedWriter() {
1315 CachedWriter &CachedWriter::operator<<(const Value &V) {
1316 assert(AW && SC && "CachedWriter does not have a current module!");
1317 if (const Instruction *I = dyn_cast<Instruction>(&V))
1319 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(&V))
1321 else if (const Function *F = dyn_cast<Function>(&V))
1323 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(&V))
1326 AW->writeOperand(&V, true, true);
1330 CachedWriter& CachedWriter::operator<<(const Type &Ty) {
1331 if (SymbolicTypes) {
1332 const Module *M = AW->getModule();
1333 if (M) WriteTypeSymbolic(Out, &Ty, M);
1340 //===----------------------------------------------------------------------===//
1341 //===-- SlotMachine Implementation
1342 //===----------------------------------------------------------------------===//
1345 #define SC_DEBUG(X) std::cerr << X
1350 // Module level constructor. Causes the contents of the Module (sans functions)
1351 // to be added to the slot table.
1352 SlotMachine::SlotMachine(const Module *M)
1353 : TheModule(M) ///< Saved for lazy initialization.
1355 , FunctionProcessed(false)
1363 // Function level constructor. Causes the contents of the Module and the one
1364 // function provided to be added to the slot table.
1365 SlotMachine::SlotMachine(const Function *F )
1366 : TheModule( F ? F->getParent() : 0 ) ///< Saved for lazy initialization
1367 , TheFunction(F) ///< Saved for lazy initialization
1368 , FunctionProcessed(false)
1376 inline void SlotMachine::initialize(void) {
1379 TheModule = 0; ///< Prevent re-processing next time we're called.
1381 if ( TheFunction && ! FunctionProcessed) {
1386 // Iterate through all the global variables, functions, and global
1387 // variable initializers and create slots for them.
1388 void SlotMachine::processModule() {
1389 SC_DEBUG("begin processModule!\n");
1391 // Add all of the global variables to the value table...
1392 for (Module::const_global_iterator I = TheModule->global_begin(), E = TheModule->global_end();
1396 // Add all the functions to the table
1397 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1401 SC_DEBUG("end processModule!\n");
1405 // Process the arguments, basic blocks, and instructions of a function.
1406 void SlotMachine::processFunction() {
1407 SC_DEBUG("begin processFunction!\n");
1409 // Add all the function arguments
1410 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1411 AE = TheFunction->arg_end(); AI != AE; ++AI)
1414 SC_DEBUG("Inserting Instructions:\n");
1416 // Add all of the basic blocks and instructions
1417 for (Function::const_iterator BB = TheFunction->begin(),
1418 E = TheFunction->end(); BB != E; ++BB) {
1420 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1425 FunctionProcessed = true;
1427 SC_DEBUG("end processFunction!\n");
1430 // Clean up after incorporating a function. This is the only way
1431 // to get out of the function incorporation state that affects the
1432 // getSlot/createSlot lock. Function incorporation state is indicated
1433 // by TheFunction != 0.
1434 void SlotMachine::purgeFunction() {
1435 SC_DEBUG("begin purgeFunction!\n");
1436 fMap.clear(); // Simply discard the function level map
1439 FunctionProcessed = false;
1440 SC_DEBUG("end purgeFunction!\n");
1443 /// Get the slot number for a value. This function will assert if you
1444 /// ask for a Value that hasn't previously been inserted with createSlot.
1445 /// Types are forbidden because Type does not inherit from Value (any more).
1446 int SlotMachine::getSlot(const Value *V) {
1447 assert( V && "Can't get slot for null Value" );
1448 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1449 "Can't insert a non-GlobalValue Constant into SlotMachine");
1451 // Check for uninitialized state and do lazy initialization
1454 // Get the type of the value
1455 const Type* VTy = V->getType();
1457 // Find the type plane in the module map
1458 TypedPlanes::const_iterator MI = mMap.find(VTy);
1460 if ( TheFunction ) {
1461 // Lookup the type in the function map too
1462 TypedPlanes::const_iterator FI = fMap.find(VTy);
1463 // If there is a corresponding type plane in the function map
1464 if ( FI != fMap.end() ) {
1465 // Lookup the Value in the function map
1466 ValueMap::const_iterator FVI = FI->second.map.find(V);
1467 // If the value doesn't exist in the function map
1468 if ( FVI == FI->second.map.end() ) {
1469 // Look up the value in the module map.
1470 if (MI == mMap.end()) return -1;
1471 ValueMap::const_iterator MVI = MI->second.map.find(V);
1472 // If we didn't find it, it wasn't inserted
1473 if (MVI == MI->second.map.end()) return -1;
1474 assert( MVI != MI->second.map.end() && "Value not found");
1475 // We found it only at the module level
1478 // else the value exists in the function map
1480 // Return the slot number as the module's contribution to
1481 // the type plane plus the index in the function's contribution
1482 // to the type plane.
1483 if (MI != mMap.end())
1484 return MI->second.next_slot + FVI->second;
1491 // N.B. Can get here only if either !TheFunction or the function doesn't
1492 // have a corresponding type plane for the Value
1494 // Make sure the type plane exists
1495 if (MI == mMap.end()) return -1;
1496 // Lookup the value in the module's map
1497 ValueMap::const_iterator MVI = MI->second.map.find(V);
1498 // Make sure we found it.
1499 if (MVI == MI->second.map.end()) return -1;
1504 /// Get the slot number for a value. This function will assert if you
1505 /// ask for a Value that hasn't previously been inserted with createSlot.
1506 /// Types are forbidden because Type does not inherit from Value (any more).
1507 int SlotMachine::getSlot(const Type *Ty) {
1508 assert( Ty && "Can't get slot for null Type" );
1510 // Check for uninitialized state and do lazy initialization
1513 if ( TheFunction ) {
1514 // Lookup the Type in the function map
1515 TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1516 // If the Type doesn't exist in the function map
1517 if ( FTI == fTypes.map.end() ) {
1518 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1519 // If we didn't find it, it wasn't inserted
1520 if (MTI == mTypes.map.end())
1522 // We found it only at the module level
1525 // else the value exists in the function map
1527 // Return the slot number as the module's contribution to
1528 // the type plane plus the index in the function's contribution
1529 // to the type plane.
1530 return mTypes.next_slot + FTI->second;
1534 // N.B. Can get here only if either !TheFunction
1536 // Lookup the value in the module's map
1537 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1538 // Make sure we found it.
1539 if (MTI == mTypes.map.end()) return -1;
1544 // Create a new slot, or return the existing slot if it is already
1545 // inserted. Note that the logic here parallels getSlot but instead
1546 // of asserting when the Value* isn't found, it inserts the value.
1547 unsigned SlotMachine::createSlot(const Value *V) {
1548 assert( V && "Can't insert a null Value to SlotMachine");
1549 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1550 "Can't insert a non-GlobalValue Constant into SlotMachine");
1552 const Type* VTy = V->getType();
1554 // Just ignore void typed things
1555 if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value!
1557 // Look up the type plane for the Value's type from the module map
1558 TypedPlanes::const_iterator MI = mMap.find(VTy);
1560 if ( TheFunction ) {
1561 // Get the type plane for the Value's type from the function map
1562 TypedPlanes::const_iterator FI = fMap.find(VTy);
1563 // If there is a corresponding type plane in the function map
1564 if ( FI != fMap.end() ) {
1565 // Lookup the Value in the function map
1566 ValueMap::const_iterator FVI = FI->second.map.find(V);
1567 // If the value doesn't exist in the function map
1568 if ( FVI == FI->second.map.end() ) {
1569 // If there is no corresponding type plane in the module map
1570 if ( MI == mMap.end() )
1571 return insertValue(V);
1572 // Look up the value in the module map
1573 ValueMap::const_iterator MVI = MI->second.map.find(V);
1574 // If we didn't find it, it wasn't inserted
1575 if ( MVI == MI->second.map.end() )
1576 return insertValue(V);
1578 // We found it only at the module level
1581 // else the value exists in the function map
1583 if ( MI == mMap.end() )
1586 // Return the slot number as the module's contribution to
1587 // the type plane plus the index in the function's contribution
1588 // to the type plane.
1589 return MI->second.next_slot + FVI->second;
1592 // else there is not a corresponding type plane in the function map
1594 // If the type plane doesn't exists at the module level
1595 if ( MI == mMap.end() ) {
1596 return insertValue(V);
1597 // else type plane exists at the module level, examine it
1599 // Look up the value in the module's map
1600 ValueMap::const_iterator MVI = MI->second.map.find(V);
1601 // If we didn't find it there either
1602 if ( MVI == MI->second.map.end() )
1603 // Return the slot number as the module's contribution to
1604 // the type plane plus the index of the function map insertion.
1605 return MI->second.next_slot + insertValue(V);
1612 // N.B. Can only get here if !TheFunction
1614 // If the module map's type plane is not for the Value's type
1615 if ( MI != mMap.end() ) {
1616 // Lookup the value in the module's map
1617 ValueMap::const_iterator MVI = MI->second.map.find(V);
1618 if ( MVI != MI->second.map.end() )
1622 return insertValue(V);
1625 // Create a new slot, or return the existing slot if it is already
1626 // inserted. Note that the logic here parallels getSlot but instead
1627 // of asserting when the Value* isn't found, it inserts the value.
1628 unsigned SlotMachine::createSlot(const Type *Ty) {
1629 assert( Ty && "Can't insert a null Type to SlotMachine");
1631 if ( TheFunction ) {
1632 // Lookup the Type in the function map
1633 TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1634 // If the type doesn't exist in the function map
1635 if ( FTI == fTypes.map.end() ) {
1636 // Look up the type in the module map
1637 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1638 // If we didn't find it, it wasn't inserted
1639 if ( MTI == mTypes.map.end() )
1640 return insertValue(Ty);
1642 // We found it only at the module level
1645 // else the value exists in the function map
1647 // Return the slot number as the module's contribution to
1648 // the type plane plus the index in the function's contribution
1649 // to the type plane.
1650 return mTypes.next_slot + FTI->second;
1654 // N.B. Can only get here if !TheFunction
1656 // Lookup the type in the module's map
1657 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1658 if ( MTI != mTypes.map.end() )
1661 return insertValue(Ty);
1664 // Low level insert function. Minimal checking is done. This
1665 // function is just for the convenience of createSlot (above).
1666 unsigned SlotMachine::insertValue(const Value *V ) {
1667 assert(V && "Can't insert a null Value into SlotMachine!");
1668 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1669 "Can't insert a non-GlobalValue Constant into SlotMachine");
1671 // If this value does not contribute to a plane (is void)
1672 // or if the value already has a name then ignore it.
1673 if (V->getType() == Type::VoidTy || V->hasName() ) {
1674 SC_DEBUG("ignored value " << *V << "\n");
1675 return 0; // FIXME: Wrong return value
1678 const Type *VTy = V->getType();
1679 unsigned DestSlot = 0;
1681 if ( TheFunction ) {
1682 TypedPlanes::iterator I = fMap.find( VTy );
1683 if ( I == fMap.end() )
1684 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1685 DestSlot = I->second.map[V] = I->second.next_slot++;
1687 TypedPlanes::iterator I = mMap.find( VTy );
1688 if ( I == mMap.end() )
1689 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1690 DestSlot = I->second.map[V] = I->second.next_slot++;
1693 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1695 // G = Global, C = Constant, T = Type, F = Function, o = other
1696 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' :
1697 (isa<Constant>(V) ? 'C' : 'o'))));
1702 // Low level insert function. Minimal checking is done. This
1703 // function is just for the convenience of createSlot (above).
1704 unsigned SlotMachine::insertValue(const Type *Ty ) {
1705 assert(Ty && "Can't insert a null Type into SlotMachine!");
1707 unsigned DestSlot = 0;
1709 if ( TheFunction ) {
1710 DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
1712 DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
1714 SC_DEBUG(" Inserting type [" << DestSlot << "] = " << Ty << "\n");