1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Assembly/CachedWriter.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/Assembly/AsmAnnotationWriter.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instruction.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Module.h"
28 #include "llvm/SymbolTable.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Streams.h"
39 // Make virtual table appear in this compilation unit.
40 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
42 /// This class provides computation of slot numbers for LLVM Assembly writing.
43 /// @brief LLVM Assembly Writing Slot Computation.
50 /// @brief A mapping of Values to slot numbers
51 typedef std::map<const Value*, unsigned> ValueMap;
53 /// @brief A plane with next slot number and ValueMap
55 unsigned next_slot; ///< The next slot number to use
56 ValueMap map; ///< The map of Value* -> unsigned
57 ValuePlane() { next_slot = 0; } ///< Make sure we start at 0
60 /// @brief The map of planes by Type
61 typedef std::map<const Type*, ValuePlane> TypedPlanes;
64 /// @name Constructors
67 /// @brief Construct from a module
68 SlotMachine(const Module *M);
70 /// @brief Construct from a function, starting out in incorp state.
71 SlotMachine(const Function *F);
77 /// Return the slot number of the specified value in it's type
78 /// plane. Its an error to ask for something not in the SlotMachine.
79 /// Its an error to ask for a Type*
80 int getSlot(const Value *V);
82 /// Determine if a Value has a slot or not
83 bool hasSlot(const Value* V);
84 bool hasSlot(const Type* Ty);
90 /// If you'd like to deal with a function instead of just a module, use
91 /// this method to get its data into the SlotMachine.
92 void incorporateFunction(const Function *F) {
94 FunctionProcessed = false;
97 /// After calling incorporateFunction, use this method to remove the
98 /// most recently incorporated function from the SlotMachine. This
99 /// will reset the state of the machine back to just the module contents.
100 void purgeFunction();
103 /// @name Implementation Details
106 /// This function does the actual initialization.
107 inline void initialize();
109 /// Values can be crammed into here at will. If they haven't
110 /// been inserted already, they get inserted, otherwise they are ignored.
111 /// Either way, the slot number for the Value* is returned.
112 unsigned getOrCreateSlot(const Value *V);
114 /// Insert a value into the value table. Return the slot number
115 /// that it now occupies. BadThings(TM) will happen if you insert a
116 /// Value that's already been inserted.
117 unsigned insertValue(const Value *V);
119 /// Add all of the module level global variables (and their initializers)
120 /// and function declarations, but not the contents of those functions.
121 void processModule();
123 /// Add all of the functions arguments, basic blocks, and instructions
124 void processFunction();
126 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
127 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
134 /// @brief The module for which we are holding slot numbers
135 const Module* TheModule;
137 /// @brief The function for which we are holding slot numbers
138 const Function* TheFunction;
139 bool FunctionProcessed;
141 /// @brief The TypePlanes map for the module level data
144 /// @brief The TypePlanes map for the function level data
151 } // end namespace llvm
153 static RegisterPass<PrintModulePass>
154 X("printm", "Print module to stderr");
155 static RegisterPass<PrintFunctionPass>
156 Y("print","Print function to stderr");
158 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
160 std::map<const Type *, std::string> &TypeTable,
161 SlotMachine *Machine);
163 static const Module *getModuleFromVal(const Value *V) {
164 if (const Argument *MA = dyn_cast<Argument>(V))
165 return MA->getParent() ? MA->getParent()->getParent() : 0;
166 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
167 return BB->getParent() ? BB->getParent()->getParent() : 0;
168 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
169 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
170 return M ? M->getParent() : 0;
171 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
172 return GV->getParent();
176 static SlotMachine *createSlotMachine(const Value *V) {
177 if (const Argument *FA = dyn_cast<Argument>(V)) {
178 return new SlotMachine(FA->getParent());
179 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
180 return new SlotMachine(I->getParent()->getParent());
181 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
182 return new SlotMachine(BB->getParent());
183 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
184 return new SlotMachine(GV->getParent());
185 } else if (const Function *Func = dyn_cast<Function>(V)) {
186 return new SlotMachine(Func);
191 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
192 // prefixed with % (if the string only contains simple characters) or is
193 // surrounded with ""'s (if it has special chars in it).
194 static std::string getLLVMName(const std::string &Name,
195 bool prefixName = true) {
196 assert(!Name.empty() && "Cannot get empty name!");
198 // First character cannot start with a number...
199 if (Name[0] >= '0' && Name[0] <= '9')
200 return "\"" + Name + "\"";
202 // Scan to see if we have any characters that are not on the "white list"
203 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
205 assert(C != '"' && "Illegal character in LLVM value name!");
206 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
207 C != '-' && C != '.' && C != '_')
208 return "\"" + Name + "\"";
211 // If we get here, then the identifier is legal to use as a "VarID".
219 /// fillTypeNameTable - If the module has a symbol table, take all global types
220 /// and stuff their names into the TypeNames map.
222 static void fillTypeNameTable(const Module *M,
223 std::map<const Type *, std::string> &TypeNames) {
225 const SymbolTable &ST = M->getSymbolTable();
226 SymbolTable::type_const_iterator TI = ST.type_begin();
227 for (; TI != ST.type_end(); ++TI) {
228 // As a heuristic, don't insert pointer to primitive types, because
229 // they are used too often to have a single useful name.
231 const Type *Ty = cast<Type>(TI->second);
232 if (!isa<PointerType>(Ty) ||
233 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
234 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
235 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
241 static void calcTypeName(const Type *Ty,
242 std::vector<const Type *> &TypeStack,
243 std::map<const Type *, std::string> &TypeNames,
244 std::string & Result){
245 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
246 Result += Ty->getDescription(); // Base case
250 // Check to see if the type is named.
251 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
252 if (I != TypeNames.end()) {
257 if (isa<OpaqueType>(Ty)) {
262 // Check to see if the Type is already on the stack...
263 unsigned Slot = 0, CurSize = TypeStack.size();
264 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
266 // This is another base case for the recursion. In this case, we know
267 // that we have looped back to a type that we have previously visited.
268 // Generate the appropriate upreference to handle this.
269 if (Slot < CurSize) {
270 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
274 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
276 switch (Ty->getTypeID()) {
277 case Type::FunctionTyID: {
278 const FunctionType *FTy = cast<FunctionType>(Ty);
279 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
281 for (FunctionType::param_iterator I = FTy->param_begin(),
282 E = FTy->param_end(); I != E; ++I) {
283 if (I != FTy->param_begin())
285 calcTypeName(*I, TypeStack, TypeNames, Result);
287 if (FTy->isVarArg()) {
288 if (FTy->getNumParams()) Result += ", ";
294 case Type::StructTyID: {
295 const StructType *STy = cast<StructType>(Ty);
297 for (StructType::element_iterator I = STy->element_begin(),
298 E = STy->element_end(); I != E; ++I) {
299 if (I != STy->element_begin())
301 calcTypeName(*I, TypeStack, TypeNames, Result);
306 case Type::PointerTyID:
307 calcTypeName(cast<PointerType>(Ty)->getElementType(),
308 TypeStack, TypeNames, Result);
311 case Type::ArrayTyID: {
312 const ArrayType *ATy = cast<ArrayType>(Ty);
313 Result += "[" + utostr(ATy->getNumElements()) + " x ";
314 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
318 case Type::PackedTyID: {
319 const PackedType *PTy = cast<PackedType>(Ty);
320 Result += "<" + utostr(PTy->getNumElements()) + " x ";
321 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
325 case Type::OpaqueTyID:
329 Result += "<unrecognized-type>";
332 TypeStack.pop_back(); // Remove self from stack...
337 /// printTypeInt - The internal guts of printing out a type that has a
338 /// potentially named portion.
340 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
341 std::map<const Type *, std::string> &TypeNames) {
342 // Primitive types always print out their description, regardless of whether
343 // they have been named or not.
345 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
346 return Out << Ty->getDescription();
348 // Check to see if the type is named.
349 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
350 if (I != TypeNames.end()) return Out << I->second;
352 // Otherwise we have a type that has not been named but is a derived type.
353 // Carefully recurse the type hierarchy to print out any contained symbolic
356 std::vector<const Type *> TypeStack;
357 std::string TypeName;
358 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
359 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
360 return (Out << TypeName);
364 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
365 /// type, iff there is an entry in the modules symbol table for the specified
366 /// type or one of it's component types. This is slower than a simple x << Type
368 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
372 // If they want us to print out a type, attempt to make it symbolic if there
373 // is a symbol table in the module...
375 std::map<const Type *, std::string> TypeNames;
376 fillTypeNameTable(M, TypeNames);
378 return printTypeInt(Out, Ty, TypeNames);
380 return Out << Ty->getDescription();
384 // PrintEscapedString - Print each character of the specified string, escaping
385 // it if it is not printable or if it is an escape char.
386 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
387 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
388 unsigned char C = Str[i];
389 if (isprint(C) && C != '"' && C != '\\') {
393 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
394 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
399 static const char * getPredicateText(unsigned predicate) {
400 const char * pred = "unknown";
402 case FCmpInst::FCMP_FALSE: pred = "false"; break;
403 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
404 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
405 case FCmpInst::FCMP_OGE: pred = "oge"; break;
406 case FCmpInst::FCMP_OLT: pred = "olt"; break;
407 case FCmpInst::FCMP_OLE: pred = "ole"; break;
408 case FCmpInst::FCMP_ONE: pred = "one"; break;
409 case FCmpInst::FCMP_ORD: pred = "ord"; break;
410 case FCmpInst::FCMP_UNO: pred = "uno"; break;
411 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
412 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
413 case FCmpInst::FCMP_UGE: pred = "uge"; break;
414 case FCmpInst::FCMP_ULT: pred = "ult"; break;
415 case FCmpInst::FCMP_ULE: pred = "ule"; break;
416 case FCmpInst::FCMP_UNE: pred = "une"; break;
417 case FCmpInst::FCMP_TRUE: pred = "true"; break;
418 case ICmpInst::ICMP_EQ: pred = "eq"; break;
419 case ICmpInst::ICMP_NE: pred = "ne"; break;
420 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
421 case ICmpInst::ICMP_SGE: pred = "sge"; break;
422 case ICmpInst::ICMP_SLT: pred = "slt"; break;
423 case ICmpInst::ICMP_SLE: pred = "sle"; break;
424 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
425 case ICmpInst::ICMP_UGE: pred = "uge"; break;
426 case ICmpInst::ICMP_ULT: pred = "ult"; break;
427 case ICmpInst::ICMP_ULE: pred = "ule"; break;
432 /// @brief Internal constant writer.
433 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
435 std::map<const Type *, std::string> &TypeTable,
436 SlotMachine *Machine) {
437 const int IndentSize = 4;
438 static std::string Indent = "\n";
439 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
440 Out << (CB->getValue() ? "true" : "false");
441 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
442 if (CI->getType()->isSigned())
443 Out << CI->getSExtValue();
445 Out << CI->getZExtValue();
446 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
447 // We would like to output the FP constant value in exponential notation,
448 // but we cannot do this if doing so will lose precision. Check here to
449 // make sure that we only output it in exponential format if we can parse
450 // the value back and get the same value.
452 std::string StrVal = ftostr(CFP->getValue());
454 // Check to make sure that the stringized number is not some string like
455 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
456 // the string matches the "[-+]?[0-9]" regex.
458 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
459 ((StrVal[0] == '-' || StrVal[0] == '+') &&
460 (StrVal[1] >= '0' && StrVal[1] <= '9')))
461 // Reparse stringized version!
462 if (atof(StrVal.c_str()) == CFP->getValue()) {
467 // Otherwise we could not reparse it to exactly the same value, so we must
468 // output the string in hexadecimal format!
469 assert(sizeof(double) == sizeof(uint64_t) &&
470 "assuming that double is 64 bits!");
471 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
473 } else if (isa<ConstantAggregateZero>(CV)) {
474 Out << "zeroinitializer";
475 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
476 // As a special case, print the array as a string if it is an array of
477 // ubytes or an array of sbytes with positive values.
479 const Type *ETy = CA->getType()->getElementType();
480 if (CA->isString()) {
482 PrintEscapedString(CA->getAsString(), Out);
485 } else { // Cannot output in string format...
487 if (CA->getNumOperands()) {
489 printTypeInt(Out, ETy, TypeTable);
490 WriteAsOperandInternal(Out, CA->getOperand(0),
491 PrintName, TypeTable, Machine);
492 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
494 printTypeInt(Out, ETy, TypeTable);
495 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
501 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
503 unsigned N = CS->getNumOperands();
506 Indent += std::string(IndentSize, ' ');
511 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
513 WriteAsOperandInternal(Out, CS->getOperand(0),
514 PrintName, TypeTable, Machine);
516 for (unsigned i = 1; i < N; i++) {
518 if (N > 2) Out << Indent;
519 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
521 WriteAsOperandInternal(Out, CS->getOperand(i),
522 PrintName, TypeTable, Machine);
524 if (N > 2) Indent.resize(Indent.size() - IndentSize);
528 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
529 const Type *ETy = CP->getType()->getElementType();
530 assert(CP->getNumOperands() > 0 &&
531 "Number of operands for a PackedConst must be > 0");
534 printTypeInt(Out, ETy, TypeTable);
535 WriteAsOperandInternal(Out, CP->getOperand(0),
536 PrintName, TypeTable, Machine);
537 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
539 printTypeInt(Out, ETy, TypeTable);
540 WriteAsOperandInternal(Out, CP->getOperand(i), PrintName,
544 } else if (isa<ConstantPointerNull>(CV)) {
547 } else if (isa<UndefValue>(CV)) {
550 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
551 Out << CE->getOpcodeName();
553 Out << " " << getPredicateText(CE->getPredicate());
556 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
557 printTypeInt(Out, (*OI)->getType(), TypeTable);
558 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
559 if (OI+1 != CE->op_end())
565 printTypeInt(Out, CE->getType(), TypeTable);
571 Out << "<placeholder or erroneous Constant>";
576 /// WriteAsOperand - Write the name of the specified value out to the specified
577 /// ostream. This can be useful when you just want to print int %reg126, not
578 /// the whole instruction that generated it.
580 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
582 std::map<const Type*, std::string> &TypeTable,
583 SlotMachine *Machine) {
585 if ((PrintName || isa<GlobalValue>(V)) && V->hasName())
586 Out << getLLVMName(V->getName());
588 const Constant *CV = dyn_cast<Constant>(V);
589 if (CV && !isa<GlobalValue>(CV)) {
590 WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
591 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
593 if (IA->hasSideEffects())
594 Out << "sideeffect ";
596 PrintEscapedString(IA->getAsmString(), Out);
598 PrintEscapedString(IA->getConstraintString(), Out);
603 Slot = Machine->getSlot(V);
605 Machine = createSlotMachine(V);
607 Slot = Machine->getSlot(V);
620 /// WriteAsOperand - Write the name of the specified value out to the specified
621 /// ostream. This can be useful when you just want to print int %reg126, not
622 /// the whole instruction that generated it.
624 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
625 bool PrintType, bool PrintName,
626 const Module *Context) {
627 std::map<const Type *, std::string> TypeNames;
628 if (Context == 0) Context = getModuleFromVal(V);
631 fillTypeNameTable(Context, TypeNames);
634 printTypeInt(Out, V->getType(), TypeNames);
636 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
643 class AssemblyWriter {
645 SlotMachine &Machine;
646 const Module *TheModule;
647 std::map<const Type *, std::string> TypeNames;
648 AssemblyAnnotationWriter *AnnotationWriter;
650 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
651 AssemblyAnnotationWriter *AAW)
652 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
654 // If the module has a symbol table, take all global types and stuff their
655 // names into the TypeNames map.
657 fillTypeNameTable(M, TypeNames);
660 inline void write(const Module *M) { printModule(M); }
661 inline void write(const GlobalVariable *G) { printGlobal(G); }
662 inline void write(const Function *F) { printFunction(F); }
663 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
664 inline void write(const Instruction *I) { printInstruction(*I); }
665 inline void write(const Constant *CPV) { printConstant(CPV); }
666 inline void write(const Type *Ty) { printType(Ty); }
668 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
670 const Module* getModule() { return TheModule; }
673 void printModule(const Module *M);
674 void printSymbolTable(const SymbolTable &ST);
675 void printConstant(const Constant *CPV);
676 void printGlobal(const GlobalVariable *GV);
677 void printFunction(const Function *F);
678 void printArgument(const Argument *FA);
679 void printBasicBlock(const BasicBlock *BB);
680 void printInstruction(const Instruction &I);
682 // printType - Go to extreme measures to attempt to print out a short,
683 // symbolic version of a type name.
685 std::ostream &printType(const Type *Ty) {
686 return printTypeInt(Out, Ty, TypeNames);
689 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
690 // without considering any symbolic types that we may have equal to it.
692 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
694 // printInfoComment - Print a little comment after the instruction indicating
695 // which slot it occupies.
696 void printInfoComment(const Value &V);
698 } // end of llvm namespace
700 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
701 /// without considering any symbolic types that we may have equal to it.
703 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
704 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
705 printType(FTy->getReturnType()) << " (";
706 for (FunctionType::param_iterator I = FTy->param_begin(),
707 E = FTy->param_end(); I != E; ++I) {
708 if (I != FTy->param_begin())
712 if (FTy->isVarArg()) {
713 if (FTy->getNumParams()) Out << ", ";
717 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
719 for (StructType::element_iterator I = STy->element_begin(),
720 E = STy->element_end(); I != E; ++I) {
721 if (I != STy->element_begin())
726 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
727 printType(PTy->getElementType()) << '*';
728 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
729 Out << '[' << ATy->getNumElements() << " x ";
730 printType(ATy->getElementType()) << ']';
731 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
732 Out << '<' << PTy->getNumElements() << " x ";
733 printType(PTy->getElementType()) << '>';
735 else if (isa<OpaqueType>(Ty)) {
738 if (!Ty->isPrimitiveType())
739 Out << "<unknown derived type>";
746 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
749 if (PrintType) { Out << ' '; printType(Operand->getType()); }
750 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Machine);
752 Out << "<null operand!>";
757 void AssemblyWriter::printModule(const Module *M) {
758 if (!M->getModuleIdentifier().empty() &&
759 // Don't print the ID if it will start a new line (which would
760 // require a comment char before it).
761 M->getModuleIdentifier().find('\n') == std::string::npos)
762 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
764 if (!M->getDataLayout().empty())
765 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
767 switch (M->getEndianness()) {
768 case Module::LittleEndian: Out << "target endian = little\n"; break;
769 case Module::BigEndian: Out << "target endian = big\n"; break;
770 case Module::AnyEndianness: break;
772 switch (M->getPointerSize()) {
773 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
774 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
775 case Module::AnyPointerSize: break;
777 if (!M->getTargetTriple().empty())
778 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
780 if (!M->getModuleInlineAsm().empty()) {
781 // Split the string into lines, to make it easier to read the .ll file.
782 std::string Asm = M->getModuleInlineAsm();
784 size_t NewLine = Asm.find_first_of('\n', CurPos);
785 while (NewLine != std::string::npos) {
786 // We found a newline, print the portion of the asm string from the
787 // last newline up to this newline.
788 Out << "module asm \"";
789 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
793 NewLine = Asm.find_first_of('\n', CurPos);
795 Out << "module asm \"";
796 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
800 // Loop over the dependent libraries and emit them.
801 Module::lib_iterator LI = M->lib_begin();
802 Module::lib_iterator LE = M->lib_end();
804 Out << "deplibs = [ ";
806 Out << '"' << *LI << '"';
814 // Loop over the symbol table, emitting all named constants.
815 printSymbolTable(M->getSymbolTable());
817 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
821 Out << "\nimplementation ; Functions:\n";
823 // Output all of the functions.
824 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
828 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
829 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
831 if (!GV->hasInitializer())
832 switch (GV->getLinkage()) {
833 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
834 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
835 default: Out << "external "; break;
838 switch (GV->getLinkage()) {
839 case GlobalValue::InternalLinkage: Out << "internal "; break;
840 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
841 case GlobalValue::WeakLinkage: Out << "weak "; break;
842 case GlobalValue::AppendingLinkage: Out << "appending "; break;
843 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
844 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
845 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
846 case GlobalValue::ExternalLinkage: break;
847 case GlobalValue::GhostLinkage:
848 llvm_cerr << "GhostLinkage not allowed in AsmWriter!\n";
852 Out << (GV->isConstant() ? "constant " : "global ");
853 printType(GV->getType()->getElementType());
855 if (GV->hasInitializer()) {
856 Constant* C = cast<Constant>(GV->getInitializer());
857 assert(C && "GlobalVar initializer isn't constant?");
858 writeOperand(GV->getInitializer(), false, isa<GlobalValue>(C));
861 if (GV->hasSection())
862 Out << ", section \"" << GV->getSection() << '"';
863 if (GV->getAlignment())
864 Out << ", align " << GV->getAlignment();
866 printInfoComment(*GV);
871 // printSymbolTable - Run through symbol table looking for constants
872 // and types. Emit their declarations.
873 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
876 for (SymbolTable::type_const_iterator TI = ST.type_begin();
877 TI != ST.type_end(); ++TI) {
878 Out << "\t" << getLLVMName(TI->first) << " = type ";
880 // Make sure we print out at least one level of the type structure, so
881 // that we do not get %FILE = type %FILE
883 printTypeAtLeastOneLevel(TI->second) << "\n";
886 // Print the constants, in type plane order.
887 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
888 PI != ST.plane_end(); ++PI) {
889 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
890 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
892 for (; VI != VE; ++VI) {
893 const Value* V = VI->second;
894 const Constant *CPV = dyn_cast<Constant>(V) ;
895 if (CPV && !isa<GlobalValue>(V)) {
903 /// printConstant - Print out a constant pool entry...
905 void AssemblyWriter::printConstant(const Constant *CPV) {
906 // Don't print out unnamed constants, they will be inlined
907 if (!CPV->hasName()) return;
910 Out << "\t" << getLLVMName(CPV->getName()) << " =";
912 // Write the value out now...
913 writeOperand(CPV, true, false);
915 printInfoComment(*CPV);
919 /// printFunction - Print all aspects of a function.
921 void AssemblyWriter::printFunction(const Function *F) {
922 // Print out the return type and name...
925 // Ensure that no local symbols conflict with global symbols.
926 const_cast<Function*>(F)->renameLocalSymbols();
928 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
931 switch (F->getLinkage()) {
932 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
933 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
934 default: Out << "declare ";
937 switch (F->getLinkage()) {
938 case GlobalValue::InternalLinkage: Out << "internal "; break;
939 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
940 case GlobalValue::WeakLinkage: Out << "weak "; break;
941 case GlobalValue::AppendingLinkage: Out << "appending "; break;
942 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
943 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
944 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
945 case GlobalValue::ExternalLinkage: break;
946 case GlobalValue::GhostLinkage:
947 llvm_cerr << "GhostLinkage not allowed in AsmWriter!\n";
951 // Print the calling convention.
952 switch (F->getCallingConv()) {
953 case CallingConv::C: break; // default
954 case CallingConv::CSRet: Out << "csretcc "; break;
955 case CallingConv::Fast: Out << "fastcc "; break;
956 case CallingConv::Cold: Out << "coldcc "; break;
957 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
958 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
959 default: Out << "cc" << F->getCallingConv() << " "; break;
962 printType(F->getReturnType()) << ' ';
963 if (!F->getName().empty())
964 Out << getLLVMName(F->getName());
968 Machine.incorporateFunction(F);
970 // Loop over the arguments, printing them...
971 const FunctionType *FT = F->getFunctionType();
973 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
977 // Finish printing arguments...
978 if (FT->isVarArg()) {
979 if (FT->getNumParams()) Out << ", ";
980 Out << "..."; // Output varargs portion of signature!
985 Out << " section \"" << F->getSection() << '"';
986 if (F->getAlignment())
987 Out << " align " << F->getAlignment();
989 if (F->isExternal()) {
994 // Output all of its basic blocks... for the function
995 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1001 Machine.purgeFunction();
1004 /// printArgument - This member is called for every argument that is passed into
1005 /// the function. Simply print it out
1007 void AssemblyWriter::printArgument(const Argument *Arg) {
1008 // Insert commas as we go... the first arg doesn't get a comma
1009 if (Arg != Arg->getParent()->arg_begin()) Out << ", ";
1012 printType(Arg->getType());
1014 // Output name, if available...
1016 Out << ' ' << getLLVMName(Arg->getName());
1019 /// printBasicBlock - This member is called for each basic block in a method.
1021 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1022 if (BB->hasName()) { // Print out the label if it exists...
1023 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1024 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1025 Out << "\n; <label>:";
1026 int Slot = Machine.getSlot(BB);
1033 if (BB->getParent() == 0)
1034 Out << "\t\t; Error: Block without parent!";
1036 if (BB != &BB->getParent()->front()) { // Not the entry block?
1037 // Output predecessors for the block...
1039 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1042 Out << " No predecessors!";
1045 writeOperand(*PI, false, true);
1046 for (++PI; PI != PE; ++PI) {
1048 writeOperand(*PI, false, true);
1056 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1058 // Output all of the instructions in the basic block...
1059 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1060 printInstruction(*I);
1062 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1066 /// printInfoComment - Print a little comment after the instruction indicating
1067 /// which slot it occupies.
1069 void AssemblyWriter::printInfoComment(const Value &V) {
1070 if (V.getType() != Type::VoidTy) {
1072 printType(V.getType()) << '>';
1075 int SlotNum = Machine.getSlot(&V);
1079 Out << ':' << SlotNum; // Print out the def slot taken.
1081 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1085 // This member is called for each Instruction in a function..
1086 void AssemblyWriter::printInstruction(const Instruction &I) {
1087 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1091 // Print out name if it exists...
1093 Out << getLLVMName(I.getName()) << " = ";
1095 // If this is a volatile load or store, print out the volatile marker.
1096 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1097 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1099 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1100 // If this is a call, check if it's a tail call.
1104 // Print out the opcode...
1105 Out << I.getOpcodeName();
1107 // Print out the compare instruction predicates
1108 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1109 Out << " " << getPredicateText(FCI->getPredicate());
1110 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1111 Out << " " << getPredicateText(ICI->getPredicate());
1114 // Print out the type of the operands...
1115 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1117 // Special case conditional branches to swizzle the condition out to the front
1118 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1119 writeOperand(I.getOperand(2), true);
1121 writeOperand(Operand, true);
1123 writeOperand(I.getOperand(1), true);
1125 } else if (isa<SwitchInst>(I)) {
1126 // Special case switch statement to get formatting nice and correct...
1127 writeOperand(Operand , true); Out << ',';
1128 writeOperand(I.getOperand(1), true); Out << " [";
1130 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1132 writeOperand(I.getOperand(op ), true); Out << ',';
1133 writeOperand(I.getOperand(op+1), true);
1136 } else if (isa<PHINode>(I)) {
1138 printType(I.getType());
1141 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1142 if (op) Out << ", ";
1144 writeOperand(I.getOperand(op ), false); Out << ',';
1145 writeOperand(I.getOperand(op+1), false); Out << " ]";
1147 } else if (isa<ReturnInst>(I) && !Operand) {
1149 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1150 // Print the calling convention being used.
1151 switch (CI->getCallingConv()) {
1152 case CallingConv::C: break; // default
1153 case CallingConv::CSRet: Out << " csretcc"; break;
1154 case CallingConv::Fast: Out << " fastcc"; break;
1155 case CallingConv::Cold: Out << " coldcc"; break;
1156 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1157 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1158 default: Out << " cc" << CI->getCallingConv(); break;
1161 const PointerType *PTy = cast<PointerType>(Operand->getType());
1162 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1163 const Type *RetTy = FTy->getReturnType();
1165 // If possible, print out the short form of the call instruction. We can
1166 // only do this if the first argument is a pointer to a nonvararg function,
1167 // and if the return type is not a pointer to a function.
1169 if (!FTy->isVarArg() &&
1170 (!isa<PointerType>(RetTy) ||
1171 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1172 Out << ' '; printType(RetTy);
1173 writeOperand(Operand, false);
1175 writeOperand(Operand, true);
1178 if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true);
1179 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
1181 writeOperand(I.getOperand(op), true);
1185 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1186 const PointerType *PTy = cast<PointerType>(Operand->getType());
1187 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1188 const Type *RetTy = FTy->getReturnType();
1190 // Print the calling convention being used.
1191 switch (II->getCallingConv()) {
1192 case CallingConv::C: break; // default
1193 case CallingConv::CSRet: Out << " csretcc"; break;
1194 case CallingConv::Fast: Out << " fastcc"; break;
1195 case CallingConv::Cold: Out << " coldcc"; break;
1196 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1197 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1198 default: Out << " cc" << II->getCallingConv(); break;
1201 // If possible, print out the short form of the invoke instruction. We can
1202 // only do this if the first argument is a pointer to a nonvararg function,
1203 // and if the return type is not a pointer to a function.
1205 if (!FTy->isVarArg() &&
1206 (!isa<PointerType>(RetTy) ||
1207 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1208 Out << ' '; printType(RetTy);
1209 writeOperand(Operand, false);
1211 writeOperand(Operand, true);
1215 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1216 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1218 writeOperand(I.getOperand(op), true);
1221 Out << " )\n\t\t\tto";
1222 writeOperand(II->getNormalDest(), true);
1224 writeOperand(II->getUnwindDest(), true);
1226 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1228 printType(AI->getType()->getElementType());
1229 if (AI->isArrayAllocation()) {
1231 writeOperand(AI->getArraySize(), true);
1233 if (AI->getAlignment()) {
1234 Out << ", align " << AI->getAlignment();
1236 } else if (isa<CastInst>(I)) {
1237 if (Operand) writeOperand(Operand, true); // Work with broken code
1239 printType(I.getType());
1240 } else if (isa<VAArgInst>(I)) {
1241 if (Operand) writeOperand(Operand, true); // Work with broken code
1243 printType(I.getType());
1244 } else if (Operand) { // Print the normal way...
1246 // PrintAllTypes - Instructions who have operands of all the same type
1247 // omit the type from all but the first operand. If the instruction has
1248 // different type operands (for example br), then they are all printed.
1249 bool PrintAllTypes = false;
1250 const Type *TheType = Operand->getType();
1252 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1253 // types even if all operands are bools.
1254 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1255 isa<ShuffleVectorInst>(I)) {
1256 PrintAllTypes = true;
1258 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1259 Operand = I.getOperand(i);
1260 if (Operand->getType() != TheType) {
1261 PrintAllTypes = true; // We have differing types! Print them all!
1267 if (!PrintAllTypes) {
1272 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1274 writeOperand(I.getOperand(i), PrintAllTypes);
1278 printInfoComment(I);
1283 //===----------------------------------------------------------------------===//
1284 // External Interface declarations
1285 //===----------------------------------------------------------------------===//
1287 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1288 SlotMachine SlotTable(this);
1289 AssemblyWriter W(o, SlotTable, this, AAW);
1293 void GlobalVariable::print(std::ostream &o) const {
1294 SlotMachine SlotTable(getParent());
1295 AssemblyWriter W(o, SlotTable, getParent(), 0);
1299 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1300 SlotMachine SlotTable(getParent());
1301 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1306 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1307 WriteAsOperand(o, this, true, true, 0);
1310 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1311 SlotMachine SlotTable(getParent());
1312 AssemblyWriter W(o, SlotTable,
1313 getParent() ? getParent()->getParent() : 0, AAW);
1317 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1318 const Function *F = getParent() ? getParent()->getParent() : 0;
1319 SlotMachine SlotTable(F);
1320 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1325 void Constant::print(std::ostream &o) const {
1326 if (this == 0) { o << "<null> constant value\n"; return; }
1328 o << ' ' << getType()->getDescription() << ' ';
1330 std::map<const Type *, std::string> TypeTable;
1331 WriteConstantInt(o, this, false, TypeTable, 0);
1334 void Type::print(std::ostream &o) const {
1338 o << getDescription();
1341 void Argument::print(std::ostream &o) const {
1342 WriteAsOperand(o, this, true, true,
1343 getParent() ? getParent()->getParent() : 0);
1346 // Value::dump - allow easy printing of Values from the debugger.
1347 // Located here because so much of the needed functionality is here.
1348 void Value::dump() const { print(std::cerr); llvm_cerr << '\n'; }
1350 // Type::dump - allow easy printing of Values from the debugger.
1351 // Located here because so much of the needed functionality is here.
1352 void Type::dump() const { print(std::cerr); llvm_cerr << '\n'; }
1354 //===----------------------------------------------------------------------===//
1355 // CachedWriter Class Implementation
1356 //===----------------------------------------------------------------------===//
1358 void CachedWriter::setModule(const Module *M) {
1359 delete SC; delete AW;
1361 SC = new SlotMachine(M);
1362 AW = new AssemblyWriter(Out, *SC, M, 0);
1368 CachedWriter::~CachedWriter() {
1373 CachedWriter &CachedWriter::operator<<(const Value &V) {
1374 assert(AW && SC && "CachedWriter does not have a current module!");
1375 if (const Instruction *I = dyn_cast<Instruction>(&V))
1377 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(&V))
1379 else if (const Function *F = dyn_cast<Function>(&V))
1381 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(&V))
1384 AW->writeOperand(&V, true, true);
1388 CachedWriter& CachedWriter::operator<<(const Type &Ty) {
1389 if (SymbolicTypes) {
1390 const Module *M = AW->getModule();
1391 if (M) WriteTypeSymbolic(Out, &Ty, M);
1398 //===----------------------------------------------------------------------===//
1399 //===-- SlotMachine Implementation
1400 //===----------------------------------------------------------------------===//
1403 #define SC_DEBUG(X) llvm_cerr << X
1408 // Module level constructor. Causes the contents of the Module (sans functions)
1409 // to be added to the slot table.
1410 SlotMachine::SlotMachine(const Module *M)
1411 : TheModule(M) ///< Saved for lazy initialization.
1413 , FunctionProcessed(false)
1417 // Function level constructor. Causes the contents of the Module and the one
1418 // function provided to be added to the slot table.
1419 SlotMachine::SlotMachine(const Function *F)
1420 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1421 , TheFunction(F) ///< Saved for lazy initialization
1422 , FunctionProcessed(false)
1426 inline void SlotMachine::initialize(void) {
1429 TheModule = 0; ///< Prevent re-processing next time we're called.
1431 if (TheFunction && !FunctionProcessed)
1435 // Iterate through all the global variables, functions, and global
1436 // variable initializers and create slots for them.
1437 void SlotMachine::processModule() {
1438 SC_DEBUG("begin processModule!\n");
1440 // Add all of the global variables to the value table...
1441 for (Module::const_global_iterator I = TheModule->global_begin(),
1442 E = TheModule->global_end(); I != E; ++I)
1445 // Add all the functions to the table
1446 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1450 SC_DEBUG("end processModule!\n");
1454 // Process the arguments, basic blocks, and instructions of a function.
1455 void SlotMachine::processFunction() {
1456 SC_DEBUG("begin processFunction!\n");
1458 // Add all the function arguments
1459 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1460 AE = TheFunction->arg_end(); AI != AE; ++AI)
1461 getOrCreateSlot(AI);
1463 SC_DEBUG("Inserting Instructions:\n");
1465 // Add all of the basic blocks and instructions
1466 for (Function::const_iterator BB = TheFunction->begin(),
1467 E = TheFunction->end(); BB != E; ++BB) {
1468 getOrCreateSlot(BB);
1469 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1473 FunctionProcessed = true;
1475 SC_DEBUG("end processFunction!\n");
1478 /// Clean up after incorporating a function. This is the only way to get out of
1479 /// the function incorporation state that affects the
1480 /// getSlot/getOrCreateSlot lock. Function incorporation state is indicated
1481 /// by TheFunction != 0.
1482 void SlotMachine::purgeFunction() {
1483 SC_DEBUG("begin purgeFunction!\n");
1484 fMap.clear(); // Simply discard the function level map
1486 FunctionProcessed = false;
1487 SC_DEBUG("end purgeFunction!\n");
1490 /// Get the slot number for a value. This function will assert if you
1491 /// ask for a Value that hasn't previously been inserted with getOrCreateSlot.
1492 /// Types are forbidden because Type does not inherit from Value (any more).
1493 int SlotMachine::getSlot(const Value *V) {
1494 assert(V && "Can't get slot for null Value");
1495 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1496 "Can't insert a non-GlobalValue Constant into SlotMachine");
1498 // Check for uninitialized state and do lazy initialization
1501 // Get the type of the value
1502 const Type* VTy = V->getType();
1504 // Find the type plane in the module map
1505 TypedPlanes::const_iterator MI = mMap.find(VTy);
1508 // Lookup the type in the function map too
1509 TypedPlanes::const_iterator FI = fMap.find(VTy);
1510 // If there is a corresponding type plane in the function map
1511 if (FI != fMap.end()) {
1512 // Lookup the Value in the function map
1513 ValueMap::const_iterator FVI = FI->second.map.find(V);
1514 // If the value doesn't exist in the function map
1515 if (FVI == FI->second.map.end()) {
1516 // Look up the value in the module map.
1517 if (MI == mMap.end()) return -1;
1518 ValueMap::const_iterator MVI = MI->second.map.find(V);
1519 // If we didn't find it, it wasn't inserted
1520 if (MVI == MI->second.map.end()) return -1;
1521 assert(MVI != MI->second.map.end() && "Value not found");
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 if (MI != mMap.end())
1531 return MI->second.next_slot + FVI->second;
1538 // N.B. Can get here only if either !TheFunction or the function doesn't
1539 // have a corresponding type plane for the Value
1541 // Make sure the type plane exists
1542 if (MI == mMap.end()) return -1;
1543 // Lookup the value in the module's map
1544 ValueMap::const_iterator MVI = MI->second.map.find(V);
1545 // Make sure we found it.
1546 if (MVI == MI->second.map.end()) return -1;
1552 // Create a new slot, or return the existing slot if it is already
1553 // inserted. Note that the logic here parallels getSlot but instead
1554 // of asserting when the Value* isn't found, it inserts the value.
1555 unsigned SlotMachine::getOrCreateSlot(const Value *V) {
1556 assert(V && "Can't insert a null Value to SlotMachine");
1557 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1558 "Can't insert a non-GlobalValue Constant into SlotMachine");
1560 const Type* VTy = V->getType();
1562 // Just ignore void typed things or things with names.
1563 if (VTy == Type::VoidTy || V->hasName())
1564 return 0; // FIXME: Wrong return value!
1566 // Look up the type plane for the Value's type from the module map
1567 TypedPlanes::const_iterator MI = mMap.find(VTy);
1570 // Get the type plane for the Value's type from the function map
1571 TypedPlanes::const_iterator FI = fMap.find(VTy);
1572 // If there is a corresponding type plane in the function map
1573 if (FI != fMap.end()) {
1574 // Lookup the Value in the function map
1575 ValueMap::const_iterator FVI = FI->second.map.find(V);
1576 // If the value doesn't exist in the function map
1577 if (FVI == FI->second.map.end()) {
1578 // If there is no corresponding type plane in the module map
1579 if (MI == mMap.end())
1580 return insertValue(V);
1581 // Look up the value in the module map
1582 ValueMap::const_iterator MVI = MI->second.map.find(V);
1583 // If we didn't find it, it wasn't inserted
1584 if (MVI == MI->second.map.end())
1585 return insertValue(V);
1587 // We found it only at the module level
1590 // else the value exists in the function map
1592 if (MI == mMap.end())
1595 // Return the slot number as the module's contribution to
1596 // the type plane plus the index in the function's contribution
1597 // to the type plane.
1598 return MI->second.next_slot + FVI->second;
1601 // else there is not a corresponding type plane in the function map
1603 // If the type plane doesn't exists at the module level
1604 if (MI == mMap.end()) {
1605 return insertValue(V);
1606 // else type plane exists at the module level, examine it
1608 // Look up the value in the module's map
1609 ValueMap::const_iterator MVI = MI->second.map.find(V);
1610 // If we didn't find it there either
1611 if (MVI == MI->second.map.end())
1612 // Return the slot number as the module's contribution to
1613 // the type plane plus the index of the function map insertion.
1614 return MI->second.next_slot + insertValue(V);
1621 // N.B. Can only get here if !TheFunction
1623 // If the module map's type plane is not for the Value's type
1624 if (MI != mMap.end()) {
1625 // Lookup the value in the module's map
1626 ValueMap::const_iterator MVI = MI->second.map.find(V);
1627 if (MVI != MI->second.map.end())
1631 return insertValue(V);
1635 // Low level insert function. Minimal checking is done. This
1636 // function is just for the convenience of getOrCreateSlot (above).
1637 unsigned SlotMachine::insertValue(const Value *V) {
1638 assert(V && "Can't insert a null Value into SlotMachine!");
1639 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1640 "Can't insert a non-GlobalValue Constant into SlotMachine");
1641 assert(V->getType() != Type::VoidTy && !V->hasName());
1643 const Type *VTy = V->getType();
1644 unsigned DestSlot = 0;
1647 TypedPlanes::iterator I = fMap.find(VTy);
1648 if (I == fMap.end())
1649 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1650 DestSlot = I->second.map[V] = I->second.next_slot++;
1652 TypedPlanes::iterator I = mMap.find(VTy);
1653 if (I == mMap.end())
1654 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1655 DestSlot = I->second.map[V] = I->second.next_slot++;
1658 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1660 // G = Global, F = Function, o = other
1661 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 'o')));