AsmWriter.cpp revision 73b7495a96e21e1515df86414e0636dbf1395fc5
1//===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This library implements the functionality defined in llvm/Assembly/Writer.h
11//
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.
14//
15//===----------------------------------------------------------------------===//
16
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/Constants.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Instruction.h"
24#include "llvm/iMemory.h"
25#include "llvm/iTerminators.h"
26#include "llvm/iPHINode.h"
27#include "llvm/iOther.h"
28#include "llvm/Module.h"
29#include "llvm/SymbolTable.h"
30#include "llvm/Assembly/Writer.h"
31#include "llvm/Support/CFG.h"
32#include "Support/StringExtras.h"
33#include "Support/STLExtras.h"
34#include <algorithm>
35using namespace llvm;
36
37namespace {
38
39/// This class provides computation of slot numbers for LLVM Assembly writing.
40/// @brief LLVM Assembly Writing Slot Computation.
41class SlotMachine {
42
43/// @name Types
44/// @{
45public:
46
47  /// @brief A mapping of Values to slot numbers
48  typedef std::map<const Value*, unsigned> ValueMap;
49
50  /// @brief A plane with next slot number and ValueMap
51  struct Plane {
52    unsigned next_slot;        ///< The next slot number to use
53    ValueMap map;              ///< The map of Value* -> unsigned
54    Plane() { next_slot = 0; } ///< Make sure we start at 0
55  };
56
57  /// @brief The map of planes by Type
58  typedef std::map<const Type*, Plane> TypedPlanes;
59
60/// @}
61/// @name Constructors
62/// @{
63public:
64  /// @brief Construct from a module
65  SlotMachine(const Module *M );
66
67  /// @brief Construct from a function, starting out in incorp state.
68  SlotMachine(const Function *F );
69
70/// @}
71/// @name Accessors
72/// @{
73public:
74  /// Return the slot number of the specified value in it's type
75  /// plane.  Its an error to ask for something not in the SlotMachine.
76  /// Its an error to ask for a Type*
77  unsigned getSlot(const Value *V) ;
78
79/// @}
80/// @name Mutators
81/// @{
82public:
83  /// If you'd like to deal with a function instead of just a module, use
84  /// this method to get its data into the SlotMachine.
85  void incorporateFunction(const Function *F) { TheFunction = F; }
86
87  /// After calling incorporateFunction, use this method to remove the
88  /// most recently incorporated function from the SlotMachine. This
89  /// will reset the state of the machine back to just the module contents.
90  void purgeFunction();
91
92/// @}
93/// @name Implementation Details
94/// @{
95private:
96  /// This function does the actual initialization.
97  inline void initialize();
98
99  /// Values can be crammed into here at will. If they haven't
100  /// been inserted already, they get inserted, otherwise they are ignored.
101  /// Either way, the slot number for the Value* is returned.
102  unsigned createSlot(const Value *V);
103
104  /// Insert a value into the value table. Return the slot number
105  /// that it now occupies.  BadThings(TM) will happen if you insert a
106  /// Value that's already been inserted.
107  unsigned insertValue( const Value *V );
108
109  /// Add all of the module level global variables (and their initializers)
110  /// and function declarations, but not the contents of those functions.
111  void processModule();
112
113  /// Add all of the functions arguments, basic blocks, and instructions
114  void processFunction();
115
116  SlotMachine(const SlotMachine &);  // DO NOT IMPLEMENT
117  void operator=(const SlotMachine &);  // DO NOT IMPLEMENT
118
119/// @}
120/// @name Data
121/// @{
122public:
123
124  /// @brief The module for which we are holding slot numbers
125  const Module* TheModule;
126
127  /// @brief The function for which we are holding slot numbers
128  const Function* TheFunction;
129
130  /// @brief The TypePlanes map for the module level data
131  TypedPlanes mMap;
132
133  /// @brief The TypePlanes map for the function level data
134  TypedPlanes fMap;
135
136/// @}
137
138};
139
140}
141
142static RegisterPass<PrintModulePass>
143X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
144static RegisterPass<PrintFunctionPass>
145Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
146
147static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
148                                   bool PrintName,
149                                 std::map<const Type *, std::string> &TypeTable,
150                                   SlotMachine *Machine);
151
152static const Module *getModuleFromVal(const Value *V) {
153  if (const Argument *MA = dyn_cast<Argument>(V))
154    return MA->getParent() ? MA->getParent()->getParent() : 0;
155  else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
156    return BB->getParent() ? BB->getParent()->getParent() : 0;
157  else if (const Instruction *I = dyn_cast<Instruction>(V)) {
158    const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
159    return M ? M->getParent() : 0;
160  } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
161    return GV->getParent();
162  return 0;
163}
164
165static SlotMachine *createSlotMachine(const Value *V) {
166  assert(!isa<Type>(V) && "Can't create an SC for a type!");
167  if (const Argument *FA = dyn_cast<Argument>(V)) {
168    return new SlotMachine(FA->getParent());
169  } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
170    return new SlotMachine(I->getParent()->getParent());
171  } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
172    return new SlotMachine(BB->getParent());
173  } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
174    return new SlotMachine(GV->getParent());
175  } else if (const Function *Func = dyn_cast<Function>(V)) {
176    return new SlotMachine(Func);
177  }
178  return 0;
179}
180
181// getLLVMName - Turn the specified string into an 'LLVM name', which is either
182// prefixed with % (if the string only contains simple characters) or is
183// surrounded with ""'s (if it has special chars in it).
184static std::string getLLVMName(const std::string &Name) {
185  assert(!Name.empty() && "Cannot get empty name!");
186
187  // First character cannot start with a number...
188  if (Name[0] >= '0' && Name[0] <= '9')
189    return "\"" + Name + "\"";
190
191  // Scan to see if we have any characters that are not on the "white list"
192  for (unsigned i = 0, e = Name.size(); i != e; ++i) {
193    char C = Name[i];
194    assert(C != '"' && "Illegal character in LLVM value name!");
195    if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
196        C != '-' && C != '.' && C != '_')
197      return "\"" + Name + "\"";
198  }
199
200  // If we get here, then the identifier is legal to use as a "VarID".
201  return "%"+Name;
202}
203
204
205/// fillTypeNameTable - If the module has a symbol table, take all global types
206/// and stuff their names into the TypeNames map.
207///
208static void fillTypeNameTable(const Module *M,
209                              std::map<const Type *, std::string> &TypeNames) {
210  if (!M) return;
211  const SymbolTable &ST = M->getSymbolTable();
212  SymbolTable::type_const_iterator TI = ST.type_begin();
213  for (; TI != ST.type_end(); ++TI ) {
214    // As a heuristic, don't insert pointer to primitive types, because
215    // they are used too often to have a single useful name.
216    //
217    const Type *Ty = cast<Type>(TI->second);
218    if (!isa<PointerType>(Ty) ||
219        !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
220        isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
221      TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
222  }
223}
224
225
226
227static std::string calcTypeName(const Type *Ty,
228                                std::vector<const Type *> &TypeStack,
229                                std::map<const Type *, std::string> &TypeNames){
230  if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
231    return Ty->getDescription();  // Base case
232
233  // Check to see if the type is named.
234  std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
235  if (I != TypeNames.end()) return I->second;
236
237  if (isa<OpaqueType>(Ty))
238    return "opaque";
239
240  // Check to see if the Type is already on the stack...
241  unsigned Slot = 0, CurSize = TypeStack.size();
242  while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
243
244  // This is another base case for the recursion.  In this case, we know
245  // that we have looped back to a type that we have previously visited.
246  // Generate the appropriate upreference to handle this.
247  if (Slot < CurSize)
248    return "\\" + utostr(CurSize-Slot);       // Here's the upreference
249
250  TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
251
252  std::string Result;
253  switch (Ty->getPrimitiveID()) {
254  case Type::FunctionTyID: {
255    const FunctionType *FTy = cast<FunctionType>(Ty);
256    Result = calcTypeName(FTy->getReturnType(), TypeStack, TypeNames) + " (";
257    for (FunctionType::param_iterator I = FTy->param_begin(),
258           E = FTy->param_end(); I != E; ++I) {
259      if (I != FTy->param_begin())
260        Result += ", ";
261      Result += calcTypeName(*I, TypeStack, TypeNames);
262    }
263    if (FTy->isVarArg()) {
264      if (FTy->getNumParams()) Result += ", ";
265      Result += "...";
266    }
267    Result += ")";
268    break;
269  }
270  case Type::StructTyID: {
271    const StructType *STy = cast<StructType>(Ty);
272    Result = "{ ";
273    for (StructType::element_iterator I = STy->element_begin(),
274           E = STy->element_end(); I != E; ++I) {
275      if (I != STy->element_begin())
276        Result += ", ";
277      Result += calcTypeName(*I, TypeStack, TypeNames);
278    }
279    Result += " }";
280    break;
281  }
282  case Type::PointerTyID:
283    Result = calcTypeName(cast<PointerType>(Ty)->getElementType(),
284                          TypeStack, TypeNames) + "*";
285    break;
286  case Type::ArrayTyID: {
287    const ArrayType *ATy = cast<ArrayType>(Ty);
288    Result = "[" + utostr(ATy->getNumElements()) + " x ";
289    Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
290    break;
291  }
292  case Type::OpaqueTyID:
293    Result = "opaque";
294    break;
295  default:
296    Result = "<unrecognized-type>";
297  }
298
299  TypeStack.pop_back();       // Remove self from stack...
300  return Result;
301}
302
303
304/// printTypeInt - The internal guts of printing out a type that has a
305/// potentially named portion.
306///
307static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
308                              std::map<const Type *, std::string> &TypeNames) {
309  // Primitive types always print out their description, regardless of whether
310  // they have been named or not.
311  //
312  if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
313    return Out << Ty->getDescription();
314
315  // Check to see if the type is named.
316  std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
317  if (I != TypeNames.end()) return Out << I->second;
318
319  // Otherwise we have a type that has not been named but is a derived type.
320  // Carefully recurse the type hierarchy to print out any contained symbolic
321  // names.
322  //
323  std::vector<const Type *> TypeStack;
324  std::string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
325  TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
326  return Out << TypeName;
327}
328
329
330/// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
331/// type, iff there is an entry in the modules symbol table for the specified
332/// type or one of it's component types. This is slower than a simple x << Type
333///
334std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
335                                      const Module *M) {
336  Out << " ";
337
338  // If they want us to print out a type, attempt to make it symbolic if there
339  // is a symbol table in the module...
340  if (M) {
341    std::map<const Type *, std::string> TypeNames;
342    fillTypeNameTable(M, TypeNames);
343
344    return printTypeInt(Out, Ty, TypeNames);
345  } else {
346    return Out << Ty->getDescription();
347  }
348}
349
350static void WriteConstantInt(std::ostream &Out, const Constant *CV,
351                             bool PrintName,
352                             std::map<const Type *, std::string> &TypeTable,
353                             SlotMachine *Machine) {
354  if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
355    Out << (CB == ConstantBool::True ? "true" : "false");
356  } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
357    Out << CI->getValue();
358  } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
359    Out << CI->getValue();
360  } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
361    // We would like to output the FP constant value in exponential notation,
362    // but we cannot do this if doing so will lose precision.  Check here to
363    // make sure that we only output it in exponential format if we can parse
364    // the value back and get the same value.
365    //
366    std::string StrVal = ftostr(CFP->getValue());
367
368    // Check to make sure that the stringized number is not some string like
369    // "Inf" or NaN, that atof will accept, but the lexer will not.  Check that
370    // the string matches the "[-+]?[0-9]" regex.
371    //
372    if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
373        ((StrVal[0] == '-' || StrVal[0] == '+') &&
374         (StrVal[1] >= '0' && StrVal[1] <= '9')))
375      // Reparse stringized version!
376      if (atof(StrVal.c_str()) == CFP->getValue()) {
377        Out << StrVal; return;
378      }
379
380    // Otherwise we could not reparse it to exactly the same value, so we must
381    // output the string in hexadecimal format!
382    //
383    // Behave nicely in the face of C TBAA rules... see:
384    // http://www.nullstone.com/htmls/category/aliastyp.htm
385    //
386    double Val = CFP->getValue();
387    char *Ptr = (char*)&Val;
388    assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
389           "assuming that double is 64 bits!");
390    Out << "0x" << utohexstr(*(uint64_t*)Ptr);
391
392  } else if (isa<ConstantAggregateZero>(CV)) {
393    Out << "zeroinitializer";
394  } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
395    // As a special case, print the array as a string if it is an array of
396    // ubytes or an array of sbytes with positive values.
397    //
398    const Type *ETy = CA->getType()->getElementType();
399    bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
400
401    if (ETy == Type::SByteTy)
402      for (unsigned i = 0; i < CA->getNumOperands(); ++i)
403        if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
404          isString = false;
405          break;
406        }
407
408    if (isString) {
409      Out << "c\"";
410      for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
411        unsigned char C = cast<ConstantInt>(CA->getOperand(i))->getRawValue();
412
413        if (isprint(C) && C != '"' && C != '\\') {
414          Out << C;
415        } else {
416          Out << '\\'
417              << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
418              << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
419        }
420      }
421      Out << "\"";
422
423    } else {                // Cannot output in string format...
424      Out << "[";
425      if (CA->getNumOperands()) {
426        Out << " ";
427        printTypeInt(Out, ETy, TypeTable);
428        WriteAsOperandInternal(Out, CA->getOperand(0),
429                               PrintName, TypeTable, Machine);
430        for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
431          Out << ", ";
432          printTypeInt(Out, ETy, TypeTable);
433          WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
434                                 TypeTable, Machine);
435        }
436      }
437      Out << " ]";
438    }
439  } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
440    Out << "{";
441    if (CS->getNumOperands()) {
442      Out << " ";
443      printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
444
445      WriteAsOperandInternal(Out, CS->getOperand(0),
446                             PrintName, TypeTable, Machine);
447
448      for (unsigned i = 1; i < CS->getNumOperands(); i++) {
449        Out << ", ";
450        printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
451
452        WriteAsOperandInternal(Out, CS->getOperand(i),
453                               PrintName, TypeTable, Machine);
454      }
455    }
456
457    Out << " }";
458  } else if (isa<ConstantPointerNull>(CV)) {
459    Out << "null";
460
461  } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
462    WriteAsOperandInternal(Out, PR->getValue(), true, TypeTable, Machine);
463
464  } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
465    Out << CE->getOpcodeName() << " (";
466
467    for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
468      printTypeInt(Out, (*OI)->getType(), TypeTable);
469      WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
470      if (OI+1 != CE->op_end())
471        Out << ", ";
472    }
473
474    if (CE->getOpcode() == Instruction::Cast) {
475      Out << " to ";
476      printTypeInt(Out, CE->getType(), TypeTable);
477    }
478    Out << ")";
479
480  } else {
481    Out << "<placeholder or erroneous Constant>";
482  }
483}
484
485
486/// WriteAsOperand - Write the name of the specified value out to the specified
487/// ostream.  This can be useful when you just want to print int %reg126, not
488/// the whole instruction that generated it.
489///
490static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
491                                   bool PrintName,
492                                  std::map<const Type*, std::string> &TypeTable,
493                                   SlotMachine *Machine) {
494  Out << " ";
495  if (PrintName && V->hasName()) {
496    Out << getLLVMName(V->getName());
497  } else {
498    if (const Constant *CV = dyn_cast<Constant>(V)) {
499      WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
500    } else {
501      int Slot;
502      if (Machine) {
503        Slot = Machine->getSlot(V);
504      } else {
505        if (const Type *Ty = dyn_cast<Type>(V)) {
506          Out << Ty->getDescription();
507          return;
508        }
509
510        Machine = createSlotMachine(V);
511        if (Machine == 0) { Out << "BAD VALUE TYPE!"; return; }
512
513        Slot = Machine->getSlot(V);
514        delete Machine;
515      }
516      Out << "%" << Slot;
517    }
518  }
519}
520
521
522/// WriteAsOperand - Write the name of the specified value out to the specified
523/// ostream.  This can be useful when you just want to print int %reg126, not
524/// the whole instruction that generated it.
525///
526std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
527                                   bool PrintType, bool PrintName,
528                                   const Module *Context) {
529  std::map<const Type *, std::string> TypeNames;
530  if (Context == 0) Context = getModuleFromVal(V);
531
532  if (Context)
533    fillTypeNameTable(Context, TypeNames);
534
535  if (PrintType)
536    printTypeInt(Out, V->getType(), TypeNames);
537
538  if (const Type *Ty = dyn_cast<Type> (V))
539    printTypeInt(Out, Ty, TypeNames);
540
541  WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
542  return Out;
543}
544
545namespace llvm {
546
547class AssemblyWriter {
548  std::ostream *Out;
549  SlotMachine &Machine;
550  const Module *TheModule;
551  std::map<const Type *, std::string> TypeNames;
552  AssemblyAnnotationWriter *AnnotationWriter;
553public:
554  inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
555                        AssemblyAnnotationWriter *AAW)
556    : Out(&o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
557
558    // If the module has a symbol table, take all global types and stuff their
559    // names into the TypeNames map.
560    //
561    fillTypeNameTable(M, TypeNames);
562  }
563
564  inline void write(const Module *M)         { printModule(M);      }
565  inline void write(const GlobalVariable *G) { printGlobal(G);      }
566  inline void write(const Function *F)       { printFunction(F);    }
567  inline void write(const BasicBlock *BB)    { printBasicBlock(BB); }
568  inline void write(const Instruction *I)    { printInstruction(*I); }
569  inline void write(const Constant *CPV)     { printConstant(CPV);  }
570  inline void write(const Type *Ty)          { printType(Ty);       }
571
572  void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
573
574  const Module* getModule() { return TheModule; }
575  void setStream(std::ostream &os) { Out = &os; }
576
577private :
578  void printModule(const Module *M);
579  void printSymbolTable(const SymbolTable &ST);
580  void printConstant(const Constant *CPV);
581  void printGlobal(const GlobalVariable *GV);
582  void printFunction(const Function *F);
583  void printArgument(const Argument *FA);
584  void printBasicBlock(const BasicBlock *BB);
585  void printInstruction(const Instruction &I);
586
587  // printType - Go to extreme measures to attempt to print out a short,
588  // symbolic version of a type name.
589  //
590  std::ostream &printType(const Type *Ty) {
591    return printTypeInt(*Out, Ty, TypeNames);
592  }
593
594  // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
595  // without considering any symbolic types that we may have equal to it.
596  //
597  std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
598
599  // printInfoComment - Print a little comment after the instruction indicating
600  // which slot it occupies.
601  void printInfoComment(const Value &V);
602};
603}  // end of llvm namespace
604
605/// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
606/// without considering any symbolic types that we may have equal to it.
607///
608std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
609  if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
610    printType(FTy->getReturnType()) << " (";
611    for (FunctionType::param_iterator I = FTy->param_begin(),
612           E = FTy->param_end(); I != E; ++I) {
613      if (I != FTy->param_begin())
614        *Out << ", ";
615      printType(*I);
616    }
617    if (FTy->isVarArg()) {
618      if (FTy->getNumParams()) *Out << ", ";
619      *Out << "...";
620    }
621    *Out << ")";
622  } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
623    *Out << "{ ";
624    for (StructType::element_iterator I = STy->element_begin(),
625           E = STy->element_end(); I != E; ++I) {
626      if (I != STy->element_begin())
627        *Out << ", ";
628      printType(*I);
629    }
630    *Out << " }";
631  } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
632    printType(PTy->getElementType()) << "*";
633  } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
634    *Out << "[" << ATy->getNumElements() << " x ";
635    printType(ATy->getElementType()) << "]";
636  } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
637    *Out << "opaque";
638  } else {
639    if (!Ty->isPrimitiveType())
640      *Out << "<unknown derived type>";
641    printType(Ty);
642  }
643  return *Out;
644}
645
646
647void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
648                                  bool PrintName) {
649  if (PrintType) { *Out << " "; printType(Operand->getType()); }
650  WriteAsOperandInternal(*Out, Operand, PrintName, TypeNames, &Machine);
651}
652
653
654void AssemblyWriter::printModule(const Module *M) {
655  switch (M->getEndianness()) {
656  case Module::LittleEndian: *Out << "target endian = little\n"; break;
657  case Module::BigEndian:    *Out << "target endian = big\n";    break;
658  case Module::AnyEndianness: break;
659  }
660  switch (M->getPointerSize()) {
661  case Module::Pointer32:    *Out << "target pointersize = 32\n"; break;
662  case Module::Pointer64:    *Out << "target pointersize = 64\n"; break;
663  case Module::AnyPointerSize: break;
664  }
665
666  // Loop over the symbol table, emitting all named constants...
667  printSymbolTable(M->getSymbolTable());
668
669  for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
670    printGlobal(I);
671
672  *Out << "\nimplementation   ; Functions:\n";
673
674  // Output all of the functions...
675  for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
676    printFunction(I);
677}
678
679void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
680  if (GV->hasName()) *Out << getLLVMName(GV->getName()) << " = ";
681
682  if (!GV->hasInitializer())
683    *Out << "external ";
684  else
685    switch (GV->getLinkage()) {
686    case GlobalValue::InternalLinkage:  *Out << "internal "; break;
687    case GlobalValue::LinkOnceLinkage:  *Out << "linkonce "; break;
688    case GlobalValue::WeakLinkage:      *Out << "weak "; break;
689    case GlobalValue::AppendingLinkage: *Out << "appending "; break;
690    case GlobalValue::ExternalLinkage: break;
691    }
692
693  *Out << (GV->isConstant() ? "constant " : "global ");
694  printType(GV->getType()->getElementType());
695
696  if (GV->hasInitializer())
697    writeOperand(GV->getInitializer(), false, false);
698
699  printInfoComment(*GV);
700  *Out << "\n";
701}
702
703
704// printSymbolTable - Run through symbol table looking for constants
705// and types. Emit their declarations.
706void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
707
708  // Print the types.
709  for (SymbolTable::type_const_iterator TI = ST.type_begin();
710       TI != ST.type_end(); ++TI ) {
711    *Out << "\t" << getLLVMName(TI->first) << " = type ";
712
713    // Make sure we print out at least one level of the type structure, so
714    // that we do not get %FILE = type %FILE
715    //
716    printTypeAtLeastOneLevel(TI->second) << "\n";
717  }
718
719  // Print the constants, in type plane order.
720  for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
721       PI != ST.plane_end(); ++PI ) {
722    SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
723    SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
724
725    for (; VI != VE; ++VI) {
726      const Value *V = VI->second;
727      if (const Constant *CPV = dyn_cast<Constant>(V)) {
728        printConstant(CPV);
729      }
730    }
731  }
732}
733
734
735/// printConstant - Print out a constant pool entry...
736///
737void AssemblyWriter::printConstant(const Constant *CPV) {
738  // Don't print out unnamed constants, they will be inlined
739  if (!CPV->hasName()) return;
740
741  // Print out name...
742  *Out << "\t" << getLLVMName(CPV->getName()) << " =";
743
744  // Write the value out now...
745  writeOperand(CPV, true, false);
746
747  printInfoComment(*CPV);
748  *Out << "\n";
749}
750
751/// printFunction - Print all aspects of a function.
752///
753void AssemblyWriter::printFunction(const Function *F) {
754  // Print out the return type and name...
755  *Out << "\n";
756
757  if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, *Out);
758
759  if (F->isExternal())
760    *Out << "declare ";
761  else
762    switch (F->getLinkage()) {
763    case GlobalValue::InternalLinkage:  *Out << "internal "; break;
764    case GlobalValue::LinkOnceLinkage:  *Out << "linkonce "; break;
765    case GlobalValue::WeakLinkage:      *Out << "weak "; break;
766    case GlobalValue::AppendingLinkage: *Out << "appending "; break;
767    case GlobalValue::ExternalLinkage: break;
768    }
769
770  printType(F->getReturnType()) << " ";
771  if (!F->getName().empty())
772    *Out << getLLVMName(F->getName());
773  else
774    *Out << "\"\"";
775  *Out << "(";
776  Machine.incorporateFunction(F);
777
778  // Loop over the arguments, printing them...
779  const FunctionType *FT = F->getFunctionType();
780
781  for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
782    printArgument(I);
783
784  // Finish printing arguments...
785  if (FT->isVarArg()) {
786    if (FT->getNumParams()) *Out << ", ";
787    *Out << "...";  // Output varargs portion of signature!
788  }
789  *Out << ")";
790
791  if (F->isExternal()) {
792    *Out << "\n";
793  } else {
794    *Out << " {";
795
796    // Output all of its basic blocks... for the function
797    for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
798      printBasicBlock(I);
799
800    *Out << "}\n";
801  }
802
803  Machine.purgeFunction();
804}
805
806/// printArgument - This member is called for every argument that is passed into
807/// the function.  Simply print it out
808///
809void AssemblyWriter::printArgument(const Argument *Arg) {
810  // Insert commas as we go... the first arg doesn't get a comma
811  if (Arg != &Arg->getParent()->afront()) *Out << ", ";
812
813  // Output type...
814  printType(Arg->getType());
815
816  // Output name, if available...
817  if (Arg->hasName())
818    *Out << " " << getLLVMName(Arg->getName());
819}
820
821/// printBasicBlock - This member is called for each basic block in a method.
822///
823void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
824  if (BB->hasName()) {              // Print out the label if it exists...
825    *Out << "\n" << BB->getName() << ":";
826  } else if (!BB->use_empty()) {      // Don't print block # of no uses...
827    *Out << "\n; <label>:" << Machine.getSlot(BB);
828  }
829
830  if (BB->getParent() == 0)
831    *Out << "\t\t; Error: Block without parent!";
832  else {
833    if (BB != &BB->getParent()->front()) {  // Not the entry block?
834      // Output predecessors for the block...
835      *Out << "\t\t;";
836      pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
837
838      if (PI == PE) {
839        *Out << " No predecessors!";
840      } else {
841        *Out << " preds =";
842        writeOperand(*PI, false, true);
843        for (++PI; PI != PE; ++PI) {
844          *Out << ",";
845          writeOperand(*PI, false, true);
846        }
847      }
848    }
849  }
850
851  *Out << "\n";
852
853  if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, *Out);
854
855  // Output all of the instructions in the basic block...
856  for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
857    printInstruction(*I);
858
859  if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, *Out);
860}
861
862
863/// printInfoComment - Print a little comment after the instruction indicating
864/// which slot it occupies.
865///
866void AssemblyWriter::printInfoComment(const Value &V) {
867  if (V.getType() != Type::VoidTy) {
868    *Out << "\t\t; <";
869    printType(V.getType()) << ">";
870
871    if (!V.hasName()) {
872      *Out << ":" << Machine.getSlot(&V); // Print out the def slot taken.
873    }
874    *Out << " [#uses=" << V.use_size() << "]";  // Output # uses
875  }
876}
877
878/// printInstruction - This member is called for each Instruction in a method.
879///
880void AssemblyWriter::printInstruction(const Instruction &I) {
881  if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, *Out);
882
883  *Out << "\t";
884
885  // Print out name if it exists...
886  if (I.hasName())
887    *Out << getLLVMName(I.getName()) << " = ";
888
889  // If this is a volatile load or store, print out the volatile marker
890  if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
891      (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
892      *Out << "volatile ";
893
894  // Print out the opcode...
895  *Out << I.getOpcodeName();
896
897  // Print out the type of the operands...
898  const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
899
900  // Special case conditional branches to swizzle the condition out to the front
901  if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
902    writeOperand(I.getOperand(2), true);
903    *Out << ",";
904    writeOperand(Operand, true);
905    *Out << ",";
906    writeOperand(I.getOperand(1), true);
907
908  } else if (isa<SwitchInst>(I)) {
909    // Special case switch statement to get formatting nice and correct...
910    writeOperand(Operand        , true); *Out << ",";
911    writeOperand(I.getOperand(1), true); *Out << " [";
912
913    for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
914      *Out << "\n\t\t";
915      writeOperand(I.getOperand(op  ), true); *Out << ",";
916      writeOperand(I.getOperand(op+1), true);
917    }
918    *Out << "\n\t]";
919  } else if (isa<PHINode>(I)) {
920    *Out << " ";
921    printType(I.getType());
922    *Out << " ";
923
924    for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
925      if (op) *Out << ", ";
926      *Out << "[";
927      writeOperand(I.getOperand(op  ), false); *Out << ",";
928      writeOperand(I.getOperand(op+1), false); *Out << " ]";
929    }
930  } else if (isa<ReturnInst>(I) && !Operand) {
931    *Out << " void";
932  } else if (isa<CallInst>(I)) {
933    const PointerType  *PTy = cast<PointerType>(Operand->getType());
934    const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
935    const Type       *RetTy = FTy->getReturnType();
936
937    // If possible, print out the short form of the call instruction.  We can
938    // only do this if the first argument is a pointer to a nonvararg function,
939    // and if the return type is not a pointer to a function.
940    //
941    if (!FTy->isVarArg() &&
942        (!isa<PointerType>(RetTy) ||
943         !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
944      *Out << " "; printType(RetTy);
945      writeOperand(Operand, false);
946    } else {
947      writeOperand(Operand, true);
948    }
949    *Out << "(";
950    if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
951    for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
952      *Out << ",";
953      writeOperand(I.getOperand(op), true);
954    }
955
956    *Out << " )";
957  } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
958    const PointerType  *PTy = cast<PointerType>(Operand->getType());
959    const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
960    const Type       *RetTy = FTy->getReturnType();
961
962    // If possible, print out the short form of the invoke instruction. We can
963    // only do this if the first argument is a pointer to a nonvararg function,
964    // and if the return type is not a pointer to a function.
965    //
966    if (!FTy->isVarArg() &&
967        (!isa<PointerType>(RetTy) ||
968         !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
969      *Out << " "; printType(RetTy);
970      writeOperand(Operand, false);
971    } else {
972      writeOperand(Operand, true);
973    }
974
975    *Out << "(";
976    if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
977    for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
978      *Out << ",";
979      writeOperand(I.getOperand(op), true);
980    }
981
982    *Out << " )\n\t\t\tto";
983    writeOperand(II->getNormalDest(), true);
984    *Out << " unwind";
985    writeOperand(II->getUnwindDest(), true);
986
987  } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
988    *Out << " ";
989    printType(AI->getType()->getElementType());
990    if (AI->isArrayAllocation()) {
991      *Out << ",";
992      writeOperand(AI->getArraySize(), true);
993    }
994  } else if (isa<CastInst>(I)) {
995    if (Operand) writeOperand(Operand, true);   // Work with broken code
996    *Out << " to ";
997    printType(I.getType());
998  } else if (isa<VAArgInst>(I)) {
999    if (Operand) writeOperand(Operand, true);   // Work with broken code
1000    *Out << ", ";
1001    printType(I.getType());
1002  } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
1003    if (Operand) writeOperand(Operand, true);   // Work with broken code
1004    *Out << ", ";
1005    printType(VAN->getArgType());
1006  } else if (Operand) {   // Print the normal way...
1007
1008    // PrintAllTypes - Instructions who have operands of all the same type
1009    // omit the type from all but the first operand.  If the instruction has
1010    // different type operands (for example br), then they are all printed.
1011    bool PrintAllTypes = false;
1012    const Type *TheType = Operand->getType();
1013
1014    // Shift Left & Right print both types even for Ubyte LHS, and select prints
1015    // types even if all operands are bools.
1016    if (isa<ShiftInst>(I) || isa<SelectInst>(I)) {
1017      PrintAllTypes = true;
1018    } else {
1019      for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1020        Operand = I.getOperand(i);
1021        if (Operand->getType() != TheType) {
1022          PrintAllTypes = true;    // We have differing types!  Print them all!
1023          break;
1024        }
1025      }
1026    }
1027
1028    if (!PrintAllTypes) {
1029      *Out << " ";
1030      printType(TheType);
1031    }
1032
1033    for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1034      if (i) *Out << ",";
1035      writeOperand(I.getOperand(i), PrintAllTypes);
1036    }
1037  }
1038
1039  printInfoComment(I);
1040  *Out << "\n";
1041}
1042
1043
1044//===----------------------------------------------------------------------===//
1045//                       External Interface declarations
1046//===----------------------------------------------------------------------===//
1047
1048void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1049  SlotMachine SlotTable(this);
1050  AssemblyWriter W(o, SlotTable, this, AAW);
1051  W.write(this);
1052}
1053
1054void GlobalVariable::print(std::ostream &o) const {
1055  SlotMachine SlotTable(getParent());
1056  AssemblyWriter W(o, SlotTable, getParent(), 0);
1057  W.write(this);
1058}
1059
1060void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1061  SlotMachine SlotTable(getParent());
1062  AssemblyWriter W(o, SlotTable, getParent(), AAW);
1063
1064  W.write(this);
1065}
1066
1067void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1068  SlotMachine SlotTable(getParent());
1069  AssemblyWriter W(o, SlotTable,
1070                   getParent() ? getParent()->getParent() : 0, AAW);
1071  W.write(this);
1072}
1073
1074void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1075  const Function *F = getParent() ? getParent()->getParent() : 0;
1076  SlotMachine SlotTable(F);
1077  AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1078
1079  W.write(this);
1080}
1081
1082void Constant::print(std::ostream &o) const {
1083  if (this == 0) { o << "<null> constant value\n"; return; }
1084
1085  // Handle CPR's special, because they have context information...
1086  if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
1087    CPR->getValue()->print(o);  // Print as a global value, with context info.
1088    return;
1089  }
1090
1091  o << " " << getType()->getDescription() << " ";
1092
1093  std::map<const Type *, std::string> TypeTable;
1094  WriteConstantInt(o, this, false, TypeTable, 0);
1095}
1096
1097void Type::print(std::ostream &o) const {
1098  if (this == 0)
1099    o << "<null Type>";
1100  else
1101    o << getDescription();
1102}
1103
1104void Argument::print(std::ostream &o) const {
1105  o << getType() << " " << getName();
1106}
1107
1108// Value::dump - allow easy printing of  Values from the debugger.
1109// Located here because so much of the needed functionality is here.
1110void Value::dump() const { print(std::cerr); }
1111
1112// Type::dump - allow easy printing of  Values from the debugger.
1113// Located here because so much of the needed functionality is here.
1114void Type::dump() const { print(std::cerr); }
1115
1116//===----------------------------------------------------------------------===//
1117//  CachedWriter Class Implementation
1118//===----------------------------------------------------------------------===//
1119
1120void CachedWriter::setModule(const Module *M) {
1121  delete SC; delete AW;
1122  if (M) {
1123    SC = new SlotMachine(M );
1124    AW = new AssemblyWriter(*Out, *SC, M, 0);
1125  } else {
1126    SC = 0; AW = 0;
1127  }
1128}
1129
1130CachedWriter::~CachedWriter() {
1131  delete AW;
1132  delete SC;
1133}
1134
1135CachedWriter &CachedWriter::operator<<(const Value *V) {
1136  assert(AW && SC && "CachedWriter does not have a current module!");
1137  switch (V->getValueType()) {
1138  case Value::ConstantVal:
1139  case Value::ArgumentVal:       AW->writeOperand(V, true, true); break;
1140  case Value::TypeVal:           AW->write(cast<Type>(V)); break;
1141  case Value::InstructionVal:    AW->write(cast<Instruction>(V)); break;
1142  case Value::BasicBlockVal:     AW->write(cast<BasicBlock>(V)); break;
1143  case Value::FunctionVal:       AW->write(cast<Function>(V)); break;
1144  case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
1145  default: *Out << "<unknown value type: " << V->getValueType() << ">"; break;
1146  }
1147  return *this;
1148}
1149
1150CachedWriter& CachedWriter::operator<<(const Type *X) {
1151  if (SymbolicTypes) {
1152    const Module *M = AW->getModule();
1153    if (M) WriteTypeSymbolic(*Out, X, M);
1154    return *this;
1155  } else
1156    return *this << (const Value*)X;
1157}
1158
1159void CachedWriter::setStream(std::ostream &os) {
1160  Out = &os;
1161  if (AW) AW->setStream(os);
1162}
1163
1164//===----------------------------------------------------------------------===//
1165//===--                    SlotMachine Implementation
1166//===----------------------------------------------------------------------===//
1167
1168#if 0
1169#define SC_DEBUG(X) std::cerr << X
1170#else
1171#define SC_DEBUG(X)
1172#endif
1173
1174// Module level constructor. Causes the contents of the Module (sans functions)
1175// to be added to the slot table.
1176SlotMachine::SlotMachine(const Module *M)
1177  : TheModule(M)    ///< Saved for lazy initialization.
1178  , TheFunction(0)
1179  , mMap()
1180  , fMap()
1181{
1182}
1183
1184// Function level constructor. Causes the contents of the Module and the one
1185// function provided to be added to the slot table.
1186SlotMachine::SlotMachine(const Function *F )
1187  : TheModule( F ? F->getParent() : 0 ) ///< Saved for lazy initialization
1188  , TheFunction(F) ///< Saved for lazy initialization
1189  , mMap()
1190  , fMap()
1191{
1192}
1193
1194inline void SlotMachine::initialize(void) {
1195  if ( TheModule) {
1196    processModule();
1197    TheModule = 0; ///< Prevent re-processing next time we're called.
1198  }
1199  if ( TheFunction ) {
1200    processFunction();
1201  }
1202}
1203
1204// Iterate through all the global variables, functions, and global
1205// variable initializers and create slots for them.
1206void SlotMachine::processModule() {
1207  SC_DEBUG("begin processModule!\n");
1208
1209  // Add all of the global variables to the value table...
1210  for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
1211       I != E; ++I)
1212    createSlot(I);
1213
1214  // Add all the functions to the table
1215  for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1216       I != E; ++I)
1217    createSlot(I);
1218
1219  SC_DEBUG("end processModule!\n");
1220}
1221
1222
1223// Process the arguments, basic blocks, and instructions  of a function.
1224void SlotMachine::processFunction() {
1225  SC_DEBUG("begin processFunction!\n");
1226
1227  // Add all the function arguments
1228  for(Function::const_aiterator AI = TheFunction->abegin(),
1229      AE = TheFunction->aend(); AI != AE; ++AI)
1230    createSlot(AI);
1231
1232  SC_DEBUG("Inserting Instructions:\n");
1233
1234  // Add all of the basic blocks and instructions
1235  for (Function::const_iterator BB = TheFunction->begin(),
1236       E = TheFunction->end(); BB != E; ++BB) {
1237    createSlot(BB);
1238    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1239      createSlot(I);
1240    }
1241  }
1242
1243  SC_DEBUG("end processFunction!\n");
1244}
1245
1246// Clean up after incorporating a function. This is the only way
1247// to get out of the function incorporation state that affects the
1248// getSlot/createSlot lock. Function incorporation state is indicated
1249// by TheFunction != 0.
1250void SlotMachine::purgeFunction() {
1251  SC_DEBUG("begin purgeFunction!\n");
1252  fMap.clear(); // Simply discard the function level map
1253  TheFunction = 0;
1254  SC_DEBUG("end purgeFunction!\n");
1255}
1256
1257/// Get the slot number for a value. This function will assert if you
1258/// ask for a Value that hasn't previously been inserted with createSlot.
1259/// Types are forbidden because Type does not inherit from Value (any more).
1260unsigned SlotMachine::getSlot(const Value *V) {
1261  assert( V && "Can't get slot for null Value" );
1262  assert( !isa<Type>(V) && "Can't get slot for a type" );
1263  assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1264    "Can't insert a non-GlobalValue Constant into SlotMachine");
1265
1266  // Check for uninitialized state and do lazy initialization
1267  this->initialize();
1268
1269  // Do not number CPR's at all. They are an abomination
1270  if ( const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(V) )
1271    V = CPR->getValue() ;
1272
1273  // Get the type of the value
1274  const Type* VTy = V->getType();
1275
1276  // Find the type plane in the module map
1277  TypedPlanes::const_iterator MI = mMap.find(VTy);
1278
1279  if ( TheFunction ) {
1280    // Lookup the type in the function map too
1281    TypedPlanes::const_iterator FI = fMap.find(VTy);
1282    // If there is a corresponding type plane in the function map
1283    if ( FI != fMap.end() ) {
1284      // Lookup the Value in the function map
1285      ValueMap::const_iterator FVI = FI->second.map.find(V);
1286      // If the value doesn't exist in the function map
1287      if ( FVI == FI->second.map.end() ) {
1288        // Look up the value in the module map
1289        ValueMap::const_iterator MVI = MI->second.map.find(V);
1290        // If we didn't find it, it wasn't inserted
1291        assert( MVI != MI->second.map.end() && "Value not found");
1292        // We found it only at the module level
1293        return MVI->second;
1294
1295      // else the value exists in the function map
1296      } else {
1297        // Return the slot number as the module's contribution to
1298        // the type plane plus the index in the function's contribution
1299        // to the type plane.
1300        return MI->second.next_slot + FVI->second;
1301      }
1302
1303    // else there is not a corresponding type plane in the function map
1304    } else  {
1305      assert( MI != mMap.end() && "No such type plane!" );
1306      // Look up the value in the module's map
1307      ValueMap::const_iterator MVI = MI->second.map.find(V);
1308      // If we didn't find it, it wasn't inserted.
1309      assert( MVI != MI->second.map.end() && "Value not found");
1310      // We found it only in the module level and function level
1311      // didn't even have a type plane.
1312      return MVI->second;
1313    }
1314  }
1315
1316  // N.B. Can only get here if !TheFunction
1317
1318  // Make sure the type plane exists
1319  assert( MI != mMap.end() && "No such type plane!" );
1320  // Lookup the value in the module's map
1321  ValueMap::const_iterator MVI = MI->second.map.find(V);
1322  // Make sure we found it.
1323  assert( MVI != MI->second.map.end() && "Value not found" );
1324  // Return it.
1325  return MVI->second;
1326}
1327
1328
1329// Create a new slot, or return the existing slot if it is already
1330// inserted. Note that the logic here parallels getSlot but instead
1331// of asserting when the Value* isn't found, it inserts the value.
1332unsigned SlotMachine::createSlot(const Value *V) {
1333  assert( V && "Can't insert a null Value to SlotMachine");
1334  assert( !isa<Type>(V) && "Can't insert a Type into SlotMachine");
1335  assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1336    "Can't insert a non-GlobalValue Constant into SlotMachine");
1337
1338  const Type* VTy = V->getType();
1339
1340  // Just ignore void typed things
1341  if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value!
1342
1343  // Look up the type plane for the Value's type from the module map
1344  TypedPlanes::const_iterator MI = mMap.find(VTy);
1345
1346  if ( TheFunction ) {
1347    // Get the type plane for the Value's type from the function map
1348    TypedPlanes::const_iterator FI = fMap.find(VTy);
1349    // If there is a corresponding type plane in the function map
1350    if ( FI != fMap.end() ) {
1351      // Lookup the Value in the function map
1352      ValueMap::const_iterator FVI = FI->second.map.find(V);
1353      // If the value doesn't exist in the function map
1354      if ( FVI == FI->second.map.end() ) {
1355        // If there is no corresponding type plane in the module map
1356        if ( MI == mMap.end() )
1357          return insertValue(V);
1358        // Look up the value in the module map
1359        ValueMap::const_iterator MVI = MI->second.map.find(V);
1360        // If we didn't find it, it wasn't inserted
1361        if ( MVI == MI->second.map.end() )
1362          return insertValue(V);
1363        else
1364          // We found it only at the module level
1365          return MVI->second;
1366
1367      // else the value exists in the function map
1368      } else {
1369        if ( MI == mMap.end() )
1370          return FVI->second;
1371        else
1372          // Return the slot number as the module's contribution to
1373          // the type plane plus the index in the function's contribution
1374          // to the type plane.
1375          return MI->second.next_slot + FVI->second;
1376      }
1377
1378    // else there is not a corresponding type plane in the function map
1379    } else {
1380      // If the type plane doesn't exists at the module level
1381      if ( MI == mMap.end() ) {
1382        return insertValue(V);
1383      // else type plane exists at the module level, examine it
1384      } else {
1385        // Look up the value in the module's map
1386        ValueMap::const_iterator MVI = MI->second.map.find(V);
1387        // If we didn't find it there either
1388        if ( MVI == MI->second.map.end() )
1389          // Return the slot number as the module's contribution to
1390          // the type plane plus the index of the function map insertion.
1391          return MI->second.next_slot + insertValue(V);
1392        else
1393          return MVI->second;
1394      }
1395    }
1396  }
1397
1398  // N.B. Can only get here if !TheFunction
1399
1400  // If the module map's type plane is not for the Value's type
1401  if ( MI != mMap.end() ) {
1402    // Lookup the value in the module's map
1403    ValueMap::const_iterator MVI = MI->second.map.find(V);
1404    if ( MVI != MI->second.map.end() )
1405      return MVI->second;
1406  }
1407
1408  return insertValue(V);
1409}
1410
1411
1412// Low level insert function. Minimal checking is done. This
1413// function is just for the convenience of createSlot (above).
1414unsigned SlotMachine::insertValue(const Value *V ) {
1415  assert(V && "Can't insert a null Value into SlotMachine!");
1416  assert(!isa<Type>(V) && "Can't insert a Type into SlotMachine!");
1417  assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1418    "Can't insert a non-GlobalValue Constant into SlotMachine");
1419
1420  // If this value does not contribute to a plane (is void)
1421  // or if the value already has a name then ignore it.
1422  if (V->getType() == Type::VoidTy || V->hasName() ) {
1423      SC_DEBUG("ignored value " << *V << "\n");
1424      return 0;   // FIXME: Wrong return value
1425  }
1426
1427  const Type *VTy = V->getType();
1428  unsigned DestSlot = 0;
1429
1430  if ( TheFunction ) {
1431    TypedPlanes::iterator I = fMap.find( VTy );
1432    if ( I == fMap.end() )
1433      I = fMap.insert(std::make_pair(VTy,Plane())).first;
1434    DestSlot = I->second.map[V] = I->second.next_slot++;
1435  } else {
1436    TypedPlanes::iterator I = mMap.find( VTy );
1437    if ( I == mMap.end() )
1438      I = mMap.insert(std::make_pair(VTy,Plane())).first;
1439    DestSlot = I->second.map[V] = I->second.next_slot++;
1440  }
1441
1442  SC_DEBUG("  Inserting value [" << VTy << "] = " << V << " slot=" <<
1443           DestSlot << " [");
1444  // G = Global, C = Constant, T = Type, F = Function, o = other
1445  SC_DEBUG((isa<GlobalVariable>(V) ? "G" : (isa<Constant>(V) ? "C" :
1446           (isa<Function>(V) ? "F" : "o"))));
1447  SC_DEBUG("]\n");
1448  return DestSlot;
1449}
1450
1451// vim: sw=2
1452