1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AsmAnnotationWriter.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/SymbolTable.h"
28 #include "llvm/TypeSymbolTable.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. If something is not in the SlotMachine, return -1.
79 int getLocalSlot(const Value *V);
80 int getGlobalSlot(const GlobalValue *V);
86 /// If you'd like to deal with a function instead of just a module, use
87 /// this method to get its data into the SlotMachine.
88 void incorporateFunction(const Function *F) {
90 FunctionProcessed = false;
93 /// After calling incorporateFunction, use this method to remove the
94 /// most recently incorporated function from the SlotMachine. This
95 /// will reset the state of the machine back to just the module contents.
99 /// @name Implementation Details
102 /// This function does the actual initialization.
103 inline void initialize();
105 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
106 void CreateModuleSlot(const GlobalValue *V);
108 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
109 void CreateFunctionSlot(const Value *V);
111 /// Add all of the module level global variables (and their initializers)
112 /// and function declarations, but not the contents of those functions.
113 void processModule();
115 /// Add all of the functions arguments, basic blocks, and instructions
116 void processFunction();
118 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
119 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
126 /// @brief The module for which we are holding slot numbers
127 const Module* TheModule;
129 /// @brief The function for which we are holding slot numbers
130 const Function* TheFunction;
131 bool FunctionProcessed;
133 /// @brief The TypePlanes map for the module level data
136 /// @brief The TypePlanes map for the function level data
143 } // end namespace llvm
145 static RegisterPass<PrintModulePass>
146 X("printm", "Print module to stderr");
147 static RegisterPass<PrintFunctionPass>
148 Y("print","Print function to stderr");
150 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
151 std::map<const Type *, std::string> &TypeTable,
152 SlotMachine *Machine);
154 static const Module *getModuleFromVal(const Value *V) {
155 if (const Argument *MA = dyn_cast<Argument>(V))
156 return MA->getParent() ? MA->getParent()->getParent() : 0;
157 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
158 return BB->getParent() ? BB->getParent()->getParent() : 0;
159 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
160 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
161 return M ? M->getParent() : 0;
162 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
163 return GV->getParent();
167 static SlotMachine *createSlotMachine(const Value *V) {
168 if (const Argument *FA = dyn_cast<Argument>(V)) {
169 return new SlotMachine(FA->getParent());
170 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
171 return new SlotMachine(I->getParent()->getParent());
172 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
173 return new SlotMachine(BB->getParent());
174 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
175 return new SlotMachine(GV->getParent());
176 } else if (const Function *Func = dyn_cast<Function>(V)) {
177 return new SlotMachine(Func);
182 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
183 // prefixed with % (if the string only contains simple characters) or is
184 // surrounded with ""'s (if it has special chars in it).
185 static std::string getLLVMName(const std::string &Name,
186 bool prefixName = true) {
187 assert(!Name.empty() && "Cannot get empty name!");
189 // First character cannot start with a number...
190 if (Name[0] >= '0' && Name[0] <= '9')
191 return "\"" + Name + "\"";
193 // Scan to see if we have any characters that are not on the "white list"
194 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
196 assert(C != '"' && "Illegal character in LLVM value name!");
197 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
198 C != '-' && C != '.' && C != '_')
199 return "\"" + Name + "\"";
202 // If we get here, then the identifier is legal to use as a "VarID".
210 /// fillTypeNameTable - If the module has a symbol table, take all global types
211 /// and stuff their names into the TypeNames map.
213 static void fillTypeNameTable(const Module *M,
214 std::map<const Type *, std::string> &TypeNames) {
216 const TypeSymbolTable &ST = M->getTypeSymbolTable();
217 TypeSymbolTable::const_iterator TI = ST.begin();
218 for (; TI != ST.end(); ++TI) {
219 // As a heuristic, don't insert pointer to primitive types, because
220 // they are used too often to have a single useful name.
222 const Type *Ty = cast<Type>(TI->second);
223 if (!isa<PointerType>(Ty) ||
224 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
225 !cast<PointerType>(Ty)->getElementType()->isIntegral() ||
226 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
227 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
233 static void calcTypeName(const Type *Ty,
234 std::vector<const Type *> &TypeStack,
235 std::map<const Type *, std::string> &TypeNames,
236 std::string & Result){
237 if (Ty->isIntegral() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
238 Result += Ty->getDescription(); // Base case
242 // Check to see if the type is named.
243 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
244 if (I != TypeNames.end()) {
249 if (isa<OpaqueType>(Ty)) {
254 // Check to see if the Type is already on the stack...
255 unsigned Slot = 0, CurSize = TypeStack.size();
256 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
258 // This is another base case for the recursion. In this case, we know
259 // that we have looped back to a type that we have previously visited.
260 // Generate the appropriate upreference to handle this.
261 if (Slot < CurSize) {
262 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
266 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
268 switch (Ty->getTypeID()) {
269 case Type::IntegerTyID: {
270 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
274 Result += "i" + utostr(BitWidth);
278 case Type::FunctionTyID: {
279 const FunctionType *FTy = cast<FunctionType>(Ty);
280 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
283 for (FunctionType::param_iterator I = FTy->param_begin(),
284 E = FTy->param_end(); I != E; ++I) {
285 if (I != FTy->param_begin())
287 calcTypeName(*I, TypeStack, TypeNames, Result);
288 if (FTy->getParamAttrs(Idx)) {
290 Result += FunctionType::getParamAttrsText(FTy->getParamAttrs(Idx));
294 if (FTy->isVarArg()) {
295 if (FTy->getNumParams()) Result += ", ";
299 if (FTy->getParamAttrs(0)) {
301 Result += FunctionType::getParamAttrsText(FTy->getParamAttrs(0));
305 case Type::StructTyID: {
306 const StructType *STy = cast<StructType>(Ty);
310 for (StructType::element_iterator I = STy->element_begin(),
311 E = STy->element_end(); I != E; ++I) {
312 if (I != STy->element_begin())
314 calcTypeName(*I, TypeStack, TypeNames, Result);
321 case Type::PointerTyID:
322 calcTypeName(cast<PointerType>(Ty)->getElementType(),
323 TypeStack, TypeNames, Result);
326 case Type::ArrayTyID: {
327 const ArrayType *ATy = cast<ArrayType>(Ty);
328 Result += "[" + utostr(ATy->getNumElements()) + " x ";
329 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
333 case Type::PackedTyID: {
334 const PackedType *PTy = cast<PackedType>(Ty);
335 Result += "<" + utostr(PTy->getNumElements()) + " x ";
336 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
340 case Type::OpaqueTyID:
344 Result += "<unrecognized-type>";
348 TypeStack.pop_back(); // Remove self from stack...
352 /// printTypeInt - The internal guts of printing out a type that has a
353 /// potentially named portion.
355 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
356 std::map<const Type *, std::string> &TypeNames) {
357 // Primitive types always print out their description, regardless of whether
358 // they have been named or not.
360 if (Ty->isIntegral() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)))
361 return Out << Ty->getDescription();
363 // Check to see if the type is named.
364 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
365 if (I != TypeNames.end()) return Out << I->second;
367 // Otherwise we have a type that has not been named but is a derived type.
368 // Carefully recurse the type hierarchy to print out any contained symbolic
371 std::vector<const Type *> TypeStack;
372 std::string TypeName;
373 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
374 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
375 return (Out << TypeName);
379 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
380 /// type, iff there is an entry in the modules symbol table for the specified
381 /// type or one of it's component types. This is slower than a simple x << Type
383 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
387 // If they want us to print out a type, but there is no context, we can't
388 // print it symbolically.
390 return Out << Ty->getDescription();
392 std::map<const Type *, std::string> TypeNames;
393 fillTypeNameTable(M, TypeNames);
394 return printTypeInt(Out, Ty, TypeNames);
397 // PrintEscapedString - Print each character of the specified string, escaping
398 // it if it is not printable or if it is an escape char.
399 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
400 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
401 unsigned char C = Str[i];
402 if (isprint(C) && C != '"' && C != '\\') {
406 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
407 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
412 static const char *getPredicateText(unsigned predicate) {
413 const char * pred = "unknown";
415 case FCmpInst::FCMP_FALSE: pred = "false"; break;
416 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
417 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
418 case FCmpInst::FCMP_OGE: pred = "oge"; break;
419 case FCmpInst::FCMP_OLT: pred = "olt"; break;
420 case FCmpInst::FCMP_OLE: pred = "ole"; break;
421 case FCmpInst::FCMP_ONE: pred = "one"; break;
422 case FCmpInst::FCMP_ORD: pred = "ord"; break;
423 case FCmpInst::FCMP_UNO: pred = "uno"; break;
424 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
425 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
426 case FCmpInst::FCMP_UGE: pred = "uge"; break;
427 case FCmpInst::FCMP_ULT: pred = "ult"; break;
428 case FCmpInst::FCMP_ULE: pred = "ule"; break;
429 case FCmpInst::FCMP_UNE: pred = "une"; break;
430 case FCmpInst::FCMP_TRUE: pred = "true"; break;
431 case ICmpInst::ICMP_EQ: pred = "eq"; break;
432 case ICmpInst::ICMP_NE: pred = "ne"; break;
433 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
434 case ICmpInst::ICMP_SGE: pred = "sge"; break;
435 case ICmpInst::ICMP_SLT: pred = "slt"; break;
436 case ICmpInst::ICMP_SLE: pred = "sle"; break;
437 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
438 case ICmpInst::ICMP_UGE: pred = "uge"; break;
439 case ICmpInst::ICMP_ULT: pred = "ult"; break;
440 case ICmpInst::ICMP_ULE: pred = "ule"; break;
445 /// @brief Internal constant writer.
446 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
447 std::map<const Type *, std::string> &TypeTable,
448 SlotMachine *Machine) {
449 const int IndentSize = 4;
450 static std::string Indent = "\n";
451 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
452 if (CI->getType() == Type::Int1Ty)
453 Out << (CI->getZExtValue() ? "true" : "false");
455 Out << CI->getSExtValue();
456 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
457 // We would like to output the FP constant value in exponential notation,
458 // but we cannot do this if doing so will lose precision. Check here to
459 // make sure that we only output it in exponential format if we can parse
460 // the value back and get the same value.
462 std::string StrVal = ftostr(CFP->getValue());
464 // Check to make sure that the stringized number is not some string like
465 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
466 // the string matches the "[-+]?[0-9]" regex.
468 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
469 ((StrVal[0] == '-' || StrVal[0] == '+') &&
470 (StrVal[1] >= '0' && StrVal[1] <= '9')))
471 // Reparse stringized version!
472 if (atof(StrVal.c_str()) == CFP->getValue()) {
477 // Otherwise we could not reparse it to exactly the same value, so we must
478 // output the string in hexadecimal format!
479 assert(sizeof(double) == sizeof(uint64_t) &&
480 "assuming that double is 64 bits!");
481 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
483 } else if (isa<ConstantAggregateZero>(CV)) {
484 Out << "zeroinitializer";
485 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
486 // As a special case, print the array as a string if it is an array of
487 // ubytes or an array of sbytes with positive values.
489 const Type *ETy = CA->getType()->getElementType();
490 if (CA->isString()) {
492 PrintEscapedString(CA->getAsString(), Out);
495 } else { // Cannot output in string format...
497 if (CA->getNumOperands()) {
499 printTypeInt(Out, ETy, TypeTable);
500 WriteAsOperandInternal(Out, CA->getOperand(0),
502 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
504 printTypeInt(Out, ETy, TypeTable);
505 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
510 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
511 if (CS->getType()->isPacked())
514 unsigned N = CS->getNumOperands();
517 Indent += std::string(IndentSize, ' ');
522 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
524 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
526 for (unsigned i = 1; i < N; i++) {
528 if (N > 2) Out << Indent;
529 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
531 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
533 if (N > 2) Indent.resize(Indent.size() - IndentSize);
537 if (CS->getType()->isPacked())
539 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
540 const Type *ETy = CP->getType()->getElementType();
541 assert(CP->getNumOperands() > 0 &&
542 "Number of operands for a PackedConst must be > 0");
545 printTypeInt(Out, ETy, TypeTable);
546 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
547 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
549 printTypeInt(Out, ETy, TypeTable);
550 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
553 } else if (isa<ConstantPointerNull>(CV)) {
556 } else if (isa<UndefValue>(CV)) {
559 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
560 Out << CE->getOpcodeName();
562 Out << " " << getPredicateText(CE->getPredicate());
565 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
566 printTypeInt(Out, (*OI)->getType(), TypeTable);
567 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
568 if (OI+1 != CE->op_end())
574 printTypeInt(Out, CE->getType(), TypeTable);
580 Out << "<placeholder or erroneous Constant>";
585 /// WriteAsOperand - Write the name of the specified value out to the specified
586 /// ostream. This can be useful when you just want to print int %reg126, not
587 /// the whole instruction that generated it.
589 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
590 std::map<const Type*, std::string> &TypeTable,
591 SlotMachine *Machine) {
594 Out << getLLVMName(V->getName());
596 const Constant *CV = dyn_cast<Constant>(V);
597 if (CV && !isa<GlobalValue>(CV)) {
598 WriteConstantInt(Out, CV, TypeTable, Machine);
599 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
601 if (IA->hasSideEffects())
602 Out << "sideeffect ";
604 PrintEscapedString(IA->getAsmString(), Out);
606 PrintEscapedString(IA->getConstraintString(), Out);
611 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
612 Slot = Machine->getGlobalSlot(GV);
614 Slot = Machine->getLocalSlot(V);
616 Machine = createSlotMachine(V);
618 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
619 Slot = Machine->getGlobalSlot(GV);
621 Slot = Machine->getLocalSlot(V);
635 /// WriteAsOperand - Write the name of the specified value out to the specified
636 /// ostream. This can be useful when you just want to print int %reg126, not
637 /// the whole instruction that generated it.
639 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
640 bool PrintType, const Module *Context) {
641 std::map<const Type *, std::string> TypeNames;
642 if (Context == 0) Context = getModuleFromVal(V);
645 fillTypeNameTable(Context, TypeNames);
648 printTypeInt(Out, V->getType(), TypeNames);
650 WriteAsOperandInternal(Out, V, 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);
684 const Module* getModule() { return TheModule; }
687 void printModule(const Module *M);
688 void printTypeSymbolTable(const TypeSymbolTable &ST);
689 void printValueSymbolTable(const SymbolTable &ST);
690 void printConstant(const Constant *CPV);
691 void printGlobal(const GlobalVariable *GV);
692 void printFunction(const Function *F);
693 void printArgument(const Argument *FA, FunctionType::ParameterAttributes A);
694 void printBasicBlock(const BasicBlock *BB);
695 void printInstruction(const Instruction &I);
697 // printType - Go to extreme measures to attempt to print out a short,
698 // symbolic version of a type name.
700 std::ostream &printType(const Type *Ty) {
701 return printTypeInt(Out, Ty, TypeNames);
704 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
705 // without considering any symbolic types that we may have equal to it.
707 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
709 // printInfoComment - Print a little comment after the instruction indicating
710 // which slot it occupies.
711 void printInfoComment(const Value &V);
713 } // end of llvm namespace
715 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
716 /// without considering any symbolic types that we may have equal to it.
718 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
719 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
720 Out << "i" << utostr(ITy->getBitWidth());
721 else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
722 printType(FTy->getReturnType());
725 for (FunctionType::param_iterator I = FTy->param_begin(),
726 E = FTy->param_end(); I != E; ++I) {
727 if (I != FTy->param_begin())
730 if (FTy->getParamAttrs(Idx)) {
731 Out << " " << FunctionType::getParamAttrsText(FTy->getParamAttrs(Idx));
735 if (FTy->isVarArg()) {
736 if (FTy->getNumParams()) Out << ", ";
740 if (FTy->getParamAttrs(0))
741 Out << ' ' << FunctionType::getParamAttrsText(FTy->getParamAttrs(0));
742 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
746 for (StructType::element_iterator I = STy->element_begin(),
747 E = STy->element_end(); I != E; ++I) {
748 if (I != STy->element_begin())
755 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
756 printType(PTy->getElementType()) << '*';
757 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
758 Out << '[' << ATy->getNumElements() << " x ";
759 printType(ATy->getElementType()) << ']';
760 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
761 Out << '<' << PTy->getNumElements() << " x ";
762 printType(PTy->getElementType()) << '>';
764 else if (isa<OpaqueType>(Ty)) {
767 if (!Ty->isPrimitiveType())
768 Out << "<unknown derived type>";
775 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
777 Out << "<null operand!>";
779 if (PrintType) { Out << ' '; printType(Operand->getType()); }
780 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
785 void AssemblyWriter::printModule(const Module *M) {
786 if (!M->getModuleIdentifier().empty() &&
787 // Don't print the ID if it will start a new line (which would
788 // require a comment char before it).
789 M->getModuleIdentifier().find('\n') == std::string::npos)
790 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
792 if (!M->getDataLayout().empty())
793 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
795 switch (M->getEndianness()) {
796 case Module::LittleEndian: Out << "target endian = little\n"; break;
797 case Module::BigEndian: Out << "target endian = big\n"; break;
798 case Module::AnyEndianness: break;
800 switch (M->getPointerSize()) {
801 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
802 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
803 case Module::AnyPointerSize: break;
805 if (!M->getTargetTriple().empty())
806 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
808 if (!M->getModuleInlineAsm().empty()) {
809 // Split the string into lines, to make it easier to read the .ll file.
810 std::string Asm = M->getModuleInlineAsm();
812 size_t NewLine = Asm.find_first_of('\n', CurPos);
813 while (NewLine != std::string::npos) {
814 // We found a newline, print the portion of the asm string from the
815 // last newline up to this newline.
816 Out << "module asm \"";
817 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
821 NewLine = Asm.find_first_of('\n', CurPos);
823 Out << "module asm \"";
824 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
828 // Loop over the dependent libraries and emit them.
829 Module::lib_iterator LI = M->lib_begin();
830 Module::lib_iterator LE = M->lib_end();
832 Out << "deplibs = [ ";
834 Out << '"' << *LI << '"';
842 // Loop over the symbol table, emitting all named constants.
843 printTypeSymbolTable(M->getTypeSymbolTable());
844 printValueSymbolTable(M->getValueSymbolTable());
846 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
850 Out << "\nimplementation ; Functions:\n";
852 // Output all of the functions.
853 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
857 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
858 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
860 if (!GV->hasInitializer())
861 switch (GV->getLinkage()) {
862 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
863 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
864 default: Out << "external "; break;
867 switch (GV->getLinkage()) {
868 case GlobalValue::InternalLinkage: Out << "internal "; break;
869 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
870 case GlobalValue::WeakLinkage: Out << "weak "; break;
871 case GlobalValue::AppendingLinkage: Out << "appending "; break;
872 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
873 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
874 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
875 case GlobalValue::ExternalLinkage: break;
876 case GlobalValue::GhostLinkage:
877 cerr << "GhostLinkage not allowed in AsmWriter!\n";
881 Out << (GV->isConstant() ? "constant " : "global ");
882 printType(GV->getType()->getElementType());
884 if (GV->hasInitializer()) {
885 Constant* C = cast<Constant>(GV->getInitializer());
886 assert(C && "GlobalVar initializer isn't constant?");
887 writeOperand(GV->getInitializer(), false);
890 if (GV->hasSection())
891 Out << ", section \"" << GV->getSection() << '"';
892 if (GV->getAlignment())
893 Out << ", align " << GV->getAlignment();
895 printInfoComment(*GV);
899 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
901 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
903 Out << "\t" << getLLVMName(TI->first) << " = type ";
905 // Make sure we print out at least one level of the type structure, so
906 // that we do not get %FILE = type %FILE
908 printTypeAtLeastOneLevel(TI->second) << "\n";
912 // printSymbolTable - Run through symbol table looking for constants
913 // and types. Emit their declarations.
914 void AssemblyWriter::printValueSymbolTable(const SymbolTable &ST) {
916 // Print the constants, in type plane order.
917 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
918 PI != ST.plane_end(); ++PI) {
919 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
920 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
922 for (; VI != VE; ++VI) {
923 const Value* V = VI->second;
924 const Constant *CPV = dyn_cast<Constant>(V) ;
925 if (CPV && !isa<GlobalValue>(V)) {
933 /// printConstant - Print out a constant pool entry...
935 void AssemblyWriter::printConstant(const Constant *CPV) {
936 // Don't print out unnamed constants, they will be inlined
937 if (!CPV->hasName()) return;
940 Out << "\t" << getLLVMName(CPV->getName()) << " =";
942 // Write the value out now.
943 writeOperand(CPV, true);
945 printInfoComment(*CPV);
949 /// printFunction - Print all aspects of a function.
951 void AssemblyWriter::printFunction(const Function *F) {
952 // Print out the return type and name...
955 // Ensure that no local symbols conflict with global symbols.
956 const_cast<Function*>(F)->renameLocalSymbols();
958 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
961 switch (F->getLinkage()) {
962 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
963 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
964 default: Out << "declare ";
968 switch (F->getLinkage()) {
969 case GlobalValue::InternalLinkage: Out << "internal "; break;
970 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
971 case GlobalValue::WeakLinkage: Out << "weak "; break;
972 case GlobalValue::AppendingLinkage: Out << "appending "; break;
973 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
974 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
975 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
976 case GlobalValue::ExternalLinkage: break;
977 case GlobalValue::GhostLinkage:
978 cerr << "GhostLinkage not allowed in AsmWriter!\n";
983 // Print the calling convention.
984 switch (F->getCallingConv()) {
985 case CallingConv::C: break; // default
986 case CallingConv::CSRet: Out << "csretcc "; break;
987 case CallingConv::Fast: Out << "fastcc "; break;
988 case CallingConv::Cold: Out << "coldcc "; break;
989 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
990 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
991 default: Out << "cc" << F->getCallingConv() << " "; break;
994 const FunctionType *FT = F->getFunctionType();
995 printType(F->getReturnType()) << ' ';
996 if (!F->getName().empty())
997 Out << getLLVMName(F->getName());
1001 Machine.incorporateFunction(F);
1003 // Loop over the arguments, printing them...
1006 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1008 // Insert commas as we go... the first arg doesn't get a comma
1009 if (I != F->arg_begin()) Out << ", ";
1010 printArgument(I, FT->getParamAttrs(Idx));
1014 // Finish printing arguments...
1015 if (FT->isVarArg()) {
1016 if (FT->getNumParams()) Out << ", ";
1017 Out << "..."; // Output varargs portion of signature!
1020 if (FT->getParamAttrs(0))
1021 Out << ' ' << FunctionType::getParamAttrsText(FT->getParamAttrs(0));
1022 if (F->hasSection())
1023 Out << " section \"" << F->getSection() << '"';
1024 if (F->getAlignment())
1025 Out << " align " << F->getAlignment();
1027 if (F->isExternal()) {
1032 // Output all of its basic blocks... for the function
1033 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1039 Machine.purgeFunction();
1042 /// printArgument - This member is called for every argument that is passed into
1043 /// the function. Simply print it out
1045 void AssemblyWriter::printArgument(const Argument *Arg,
1046 FunctionType::ParameterAttributes attrs) {
1048 printType(Arg->getType());
1050 if (attrs != FunctionType::NoAttributeSet)
1051 Out << ' ' << FunctionType::getParamAttrsText(attrs);
1053 // Output name, if available...
1055 Out << ' ' << getLLVMName(Arg->getName());
1058 /// printBasicBlock - This member is called for each basic block in a method.
1060 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1061 if (BB->hasName()) { // Print out the label if it exists...
1062 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1063 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1064 Out << "\n; <label>:";
1065 int Slot = Machine.getLocalSlot(BB);
1072 if (BB->getParent() == 0)
1073 Out << "\t\t; Error: Block without parent!";
1075 if (BB != &BB->getParent()->front()) { // Not the entry block?
1076 // Output predecessors for the block...
1078 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1081 Out << " No predecessors!";
1084 writeOperand(*PI, false);
1085 for (++PI; PI != PE; ++PI) {
1087 writeOperand(*PI, false);
1095 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1097 // Output all of the instructions in the basic block...
1098 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1099 printInstruction(*I);
1101 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1105 /// printInfoComment - Print a little comment after the instruction indicating
1106 /// which slot it occupies.
1108 void AssemblyWriter::printInfoComment(const Value &V) {
1109 if (V.getType() != Type::VoidTy) {
1111 printType(V.getType()) << '>';
1115 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1116 SlotNum = Machine.getGlobalSlot(GV);
1118 SlotNum = Machine.getLocalSlot(&V);
1122 Out << ':' << SlotNum; // Print out the def slot taken.
1124 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1128 // This member is called for each Instruction in a function..
1129 void AssemblyWriter::printInstruction(const Instruction &I) {
1130 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1134 // Print out name if it exists...
1136 Out << getLLVMName(I.getName()) << " = ";
1138 // If this is a volatile load or store, print out the volatile marker.
1139 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1140 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1142 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1143 // If this is a call, check if it's a tail call.
1147 // Print out the opcode...
1148 Out << I.getOpcodeName();
1150 // Print out the compare instruction predicates
1151 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1152 Out << " " << getPredicateText(FCI->getPredicate());
1153 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1154 Out << " " << getPredicateText(ICI->getPredicate());
1157 // Print out the type of the operands...
1158 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1160 // Special case conditional branches to swizzle the condition out to the front
1161 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1162 writeOperand(I.getOperand(2), true);
1164 writeOperand(Operand, true);
1166 writeOperand(I.getOperand(1), true);
1168 } else if (isa<SwitchInst>(I)) {
1169 // Special case switch statement to get formatting nice and correct...
1170 writeOperand(Operand , true); Out << ',';
1171 writeOperand(I.getOperand(1), true); Out << " [";
1173 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1175 writeOperand(I.getOperand(op ), true); Out << ',';
1176 writeOperand(I.getOperand(op+1), true);
1179 } else if (isa<PHINode>(I)) {
1181 printType(I.getType());
1184 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1185 if (op) Out << ", ";
1187 writeOperand(I.getOperand(op ), false); Out << ',';
1188 writeOperand(I.getOperand(op+1), false); Out << " ]";
1190 } else if (isa<ReturnInst>(I) && !Operand) {
1192 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1193 // Print the calling convention being used.
1194 switch (CI->getCallingConv()) {
1195 case CallingConv::C: break; // default
1196 case CallingConv::CSRet: Out << " csretcc"; break;
1197 case CallingConv::Fast: Out << " fastcc"; break;
1198 case CallingConv::Cold: Out << " coldcc"; break;
1199 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1200 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1201 default: Out << " cc" << CI->getCallingConv(); break;
1204 const PointerType *PTy = cast<PointerType>(Operand->getType());
1205 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1206 const Type *RetTy = FTy->getReturnType();
1208 // If possible, print out the short form of the call instruction. We can
1209 // only do this if the first argument is a pointer to a nonvararg function,
1210 // and if the return type is not a pointer to a function.
1212 if (!FTy->isVarArg() &&
1213 (!isa<PointerType>(RetTy) ||
1214 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1215 Out << ' '; printType(RetTy);
1216 writeOperand(Operand, false);
1218 writeOperand(Operand, true);
1221 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1224 writeOperand(I.getOperand(op), true);
1225 if (FTy->getParamAttrs(op) != FunctionType::NoAttributeSet)
1226 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op));
1229 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet)
1230 Out << ' ' << FTy->getParamAttrsText(FTy->getParamAttrs(0));
1231 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1232 const PointerType *PTy = cast<PointerType>(Operand->getType());
1233 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1234 const Type *RetTy = FTy->getReturnType();
1236 // Print the calling convention being used.
1237 switch (II->getCallingConv()) {
1238 case CallingConv::C: break; // default
1239 case CallingConv::CSRet: Out << " csretcc"; break;
1240 case CallingConv::Fast: Out << " fastcc"; break;
1241 case CallingConv::Cold: Out << " coldcc"; break;
1242 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1243 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1244 default: Out << " cc" << II->getCallingConv(); break;
1247 // If possible, print out the short form of the invoke instruction. We can
1248 // only do this if the first argument is a pointer to a nonvararg function,
1249 // and if the return type is not a pointer to a function.
1251 if (!FTy->isVarArg() &&
1252 (!isa<PointerType>(RetTy) ||
1253 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1254 Out << ' '; printType(RetTy);
1255 writeOperand(Operand, false);
1257 writeOperand(Operand, true);
1261 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1264 writeOperand(I.getOperand(op), true);
1265 if (FTy->getParamAttrs(op-2) != FunctionType::NoAttributeSet)
1266 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op-2));
1270 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet)
1271 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(0));
1272 Out << "\n\t\t\tto";
1273 writeOperand(II->getNormalDest(), true);
1275 writeOperand(II->getUnwindDest(), true);
1277 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1279 printType(AI->getType()->getElementType());
1280 if (AI->isArrayAllocation()) {
1282 writeOperand(AI->getArraySize(), true);
1284 if (AI->getAlignment()) {
1285 Out << ", align " << AI->getAlignment();
1287 } else if (isa<CastInst>(I)) {
1288 if (Operand) writeOperand(Operand, true); // Work with broken code
1290 printType(I.getType());
1291 } else if (isa<VAArgInst>(I)) {
1292 if (Operand) writeOperand(Operand, true); // Work with broken code
1294 printType(I.getType());
1295 } else if (Operand) { // Print the normal way...
1297 // PrintAllTypes - Instructions who have operands of all the same type
1298 // omit the type from all but the first operand. If the instruction has
1299 // different type operands (for example br), then they are all printed.
1300 bool PrintAllTypes = false;
1301 const Type *TheType = Operand->getType();
1303 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1304 // types even if all operands are bools.
1305 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1306 isa<ShuffleVectorInst>(I)) {
1307 PrintAllTypes = true;
1309 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1310 Operand = I.getOperand(i);
1311 if (Operand->getType() != TheType) {
1312 PrintAllTypes = true; // We have differing types! Print them all!
1318 if (!PrintAllTypes) {
1323 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1325 writeOperand(I.getOperand(i), PrintAllTypes);
1329 printInfoComment(I);
1334 //===----------------------------------------------------------------------===//
1335 // External Interface declarations
1336 //===----------------------------------------------------------------------===//
1338 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1339 SlotMachine SlotTable(this);
1340 AssemblyWriter W(o, SlotTable, this, AAW);
1344 void GlobalVariable::print(std::ostream &o) const {
1345 SlotMachine SlotTable(getParent());
1346 AssemblyWriter W(o, SlotTable, getParent(), 0);
1350 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1351 SlotMachine SlotTable(getParent());
1352 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1357 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1358 WriteAsOperand(o, this, true, 0);
1361 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1362 SlotMachine SlotTable(getParent());
1363 AssemblyWriter W(o, SlotTable,
1364 getParent() ? getParent()->getParent() : 0, AAW);
1368 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1369 const Function *F = getParent() ? getParent()->getParent() : 0;
1370 SlotMachine SlotTable(F);
1371 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1376 void Constant::print(std::ostream &o) const {
1377 if (this == 0) { o << "<null> constant value\n"; return; }
1379 o << ' ' << getType()->getDescription() << ' ';
1381 std::map<const Type *, std::string> TypeTable;
1382 WriteConstantInt(o, this, TypeTable, 0);
1385 void Type::print(std::ostream &o) const {
1389 o << getDescription();
1392 void Argument::print(std::ostream &o) const {
1393 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1396 // Value::dump - allow easy printing of Values from the debugger.
1397 // Located here because so much of the needed functionality is here.
1398 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1400 // Type::dump - allow easy printing of Values from the debugger.
1401 // Located here because so much of the needed functionality is here.
1402 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1404 //===----------------------------------------------------------------------===//
1405 // SlotMachine Implementation
1406 //===----------------------------------------------------------------------===//
1409 #define SC_DEBUG(X) cerr << X
1414 // Module level constructor. Causes the contents of the Module (sans functions)
1415 // to be added to the slot table.
1416 SlotMachine::SlotMachine(const Module *M)
1417 : TheModule(M) ///< Saved for lazy initialization.
1419 , FunctionProcessed(false)
1423 // Function level constructor. Causes the contents of the Module and the one
1424 // function provided to be added to the slot table.
1425 SlotMachine::SlotMachine(const Function *F)
1426 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1427 , TheFunction(F) ///< Saved for lazy initialization
1428 , FunctionProcessed(false)
1432 inline void SlotMachine::initialize() {
1435 TheModule = 0; ///< Prevent re-processing next time we're called.
1437 if (TheFunction && !FunctionProcessed)
1441 // Iterate through all the global variables, functions, and global
1442 // variable initializers and create slots for them.
1443 void SlotMachine::processModule() {
1444 SC_DEBUG("begin processModule!\n");
1446 // Add all of the unnamed global variables to the value table.
1447 for (Module::const_global_iterator I = TheModule->global_begin(),
1448 E = TheModule->global_end(); I != E; ++I)
1450 CreateModuleSlot(I);
1452 // Add all the unnamed functions to the table.
1453 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1456 CreateModuleSlot(I);
1458 SC_DEBUG("end processModule!\n");
1462 // Process the arguments, basic blocks, and instructions of a function.
1463 void SlotMachine::processFunction() {
1464 SC_DEBUG("begin processFunction!\n");
1466 // Add all the function arguments with no names.
1467 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1468 AE = TheFunction->arg_end(); AI != AE; ++AI)
1470 CreateFunctionSlot(AI);
1472 SC_DEBUG("Inserting Instructions:\n");
1474 // Add all of the basic blocks and instructions with no names.
1475 for (Function::const_iterator BB = TheFunction->begin(),
1476 E = TheFunction->end(); BB != E; ++BB) {
1478 CreateFunctionSlot(BB);
1479 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1480 if (I->getType() != Type::VoidTy && !I->hasName())
1481 CreateFunctionSlot(I);
1484 FunctionProcessed = true;
1486 SC_DEBUG("end processFunction!\n");
1489 /// Clean up after incorporating a function. This is the only way to get out of
1490 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1491 /// incorporation state is indicated by TheFunction != 0.
1492 void SlotMachine::purgeFunction() {
1493 SC_DEBUG("begin purgeFunction!\n");
1494 fMap.clear(); // Simply discard the function level map
1496 FunctionProcessed = false;
1497 SC_DEBUG("end purgeFunction!\n");
1500 /// getGlobalSlot - Get the slot number of a global value.
1501 int SlotMachine::getGlobalSlot(const GlobalValue *V) {
1502 // Check for uninitialized state and do lazy initialization.
1505 // Find the type plane in the module map
1506 TypedPlanes::const_iterator MI = mMap.find(V->getType());
1507 if (MI == mMap.end()) return -1;
1509 // Lookup the value in the module plane's map.
1510 ValueMap::const_iterator MVI = MI->second.map.find(V);
1511 return MVI != MI->second.map.end() ? int(MVI->second) : -1;
1515 /// getLocalSlot - Get the slot number for a value that is local to a function.
1516 int SlotMachine::getLocalSlot(const Value *V) {
1517 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1519 // Check for uninitialized state and do lazy initialization.
1522 // Get the type of the value
1523 const Type *VTy = V->getType();
1525 TypedPlanes::const_iterator FI = fMap.find(VTy);
1526 if (FI == fMap.end()) return -1;
1528 // Lookup the Value in the function and module maps.
1529 ValueMap::const_iterator FVI = FI->second.map.find(V);
1530 TypedPlanes::const_iterator MI = mMap.find(VTy);
1532 // If the value doesn't exist in the function map, it is a <badref>
1533 if (FVI == FI->second.map.end()) return -1;
1535 // Return the slot number as the module's contribution to
1536 // the type plane plus the index in the function's contribution
1537 // to the type plane.
1538 if (MI != mMap.end())
1539 return MI->second.next_slot + FVI->second;
1545 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1546 void SlotMachine::CreateModuleSlot(const GlobalValue *V) {
1547 assert(V && "Can't insert a null Value into SlotMachine!");
1549 unsigned DestSlot = 0;
1550 const Type *VTy = V->getType();
1552 ValuePlane &PlaneMap = mMap[VTy];
1553 DestSlot = PlaneMap.map[V] = PlaneMap.next_slot++;
1555 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1557 // G = Global, F = Function, o = other
1558 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : 'F') << "]\n");
1562 /// CreateSlot - Create a new slot for the specified value if it has no name.
1563 void SlotMachine::CreateFunctionSlot(const Value *V) {
1564 const Type *VTy = V->getType();
1565 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1567 unsigned DestSlot = 0;
1569 ValuePlane &PlaneMap = fMap[VTy];
1570 DestSlot = PlaneMap.map[V] = PlaneMap.next_slot++;
1572 // G = Global, F = Function, o = other
1573 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1574 DestSlot << " [o]\n");