AsmWriter.cpp revision 31f8499e83dc4dccbb57ea7e76d1fd49b7010d0c
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/SlotCalculator.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Instruction.h"
24#include "llvm/Module.h"
25#include "llvm/Constants.h"
26#include "llvm/iMemory.h"
27#include "llvm/iTerminators.h"
28#include "llvm/iPHINode.h"
29#include "llvm/iOther.h"
30#include "llvm/SymbolTable.h"
31#include "llvm/Support/CFG.h"
32#include "Support/StringExtras.h"
33#include "Support/STLExtras.h"
34#include <algorithm>
35using namespace llvm;
36
37static RegisterPass<PrintModulePass>
38X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
39static RegisterPass<PrintFunctionPass>
40Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
41
42static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
43                                   bool PrintName,
44                                 std::map<const Type *, std::string> &TypeTable,
45                                   SlotCalculator *Table);
46
47static const Module *getModuleFromVal(const Value *V) {
48  if (const Argument *MA = dyn_cast<Argument>(V))
49    return MA->getParent() ? MA->getParent()->getParent() : 0;
50  else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
51    return BB->getParent() ? BB->getParent()->getParent() : 0;
52  else if (const Instruction *I = dyn_cast<Instruction>(V)) {
53    const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
54    return M ? M->getParent() : 0;
55  } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
56    return GV->getParent();
57  return 0;
58}
59
60static SlotCalculator *createSlotCalculator(const Value *V) {
61  assert(!isa<Type>(V) && "Can't create an SC for a type!");
62  if (const Argument *FA = dyn_cast<Argument>(V)) {
63    return new SlotCalculator(FA->getParent(), true);
64  } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
65    return new SlotCalculator(I->getParent()->getParent(), true);
66  } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
67    return new SlotCalculator(BB->getParent(), true);
68  } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
69    return new SlotCalculator(GV->getParent(), true);
70  } else if (const Function *Func = dyn_cast<Function>(V)) {
71    return new SlotCalculator(Func, true);
72  }
73  return 0;
74}
75
76// getLLVMName - Turn the specified string into an 'LLVM name', which is either
77// prefixed with % (if the string only contains simple characters) or is
78// surrounded with ""'s (if it has special chars in it).
79static std::string getLLVMName(const std::string &Name) {
80  assert(!Name.empty() && "Cannot get empty name!");
81
82  // First character cannot start with a number...
83  if (Name[0] >= '0' && Name[0] <= '9')
84    return "\"" + Name + "\"";
85
86  // Scan to see if we have any characters that are not on the "white list"
87  for (unsigned i = 0, e = Name.size(); i != e; ++i) {
88    char C = Name[i];
89    assert(C != '"' && "Illegal character in LLVM value name!");
90    if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
91        C != '-' && C != '.' && C != '_')
92      return "\"" + Name + "\"";
93  }
94
95  // If we get here, then the identifier is legal to use as a "VarID".
96  return "%"+Name;
97}
98
99
100// If the module has a symbol table, take all global types and stuff their
101// names into the TypeNames map.
102//
103static void fillTypeNameTable(const Module *M,
104                              std::map<const Type *, std::string> &TypeNames) {
105  if (!M) return;
106  const SymbolTable &ST = M->getSymbolTable();
107  SymbolTable::const_iterator PI = ST.find(Type::TypeTy);
108  if (PI != ST.end()) {
109    SymbolTable::type_const_iterator I = PI->second.begin();
110    for (; I != PI->second.end(); ++I) {
111      // As a heuristic, don't insert pointer to primitive types, because
112      // they are used too often to have a single useful name.
113      //
114      const Type *Ty = cast<Type>(I->second);
115      if (!isa<PointerType>(Ty) ||
116          !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
117          isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
118        TypeNames.insert(std::make_pair(Ty, getLLVMName(I->first)));
119    }
120  }
121}
122
123
124
125static std::string calcTypeName(const Type *Ty,
126                                std::vector<const Type *> &TypeStack,
127                                std::map<const Type *, std::string> &TypeNames){
128  if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
129    return Ty->getDescription();  // Base case
130
131  // Check to see if the type is named.
132  std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
133  if (I != TypeNames.end()) return I->second;
134
135  if (isa<OpaqueType>(Ty))
136    return "opaque";
137
138  // Check to see if the Type is already on the stack...
139  unsigned Slot = 0, CurSize = TypeStack.size();
140  while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
141
142  // This is another base case for the recursion.  In this case, we know
143  // that we have looped back to a type that we have previously visited.
144  // Generate the appropriate upreference to handle this.
145  //
146  if (Slot < CurSize)
147    return "\\" + utostr(CurSize-Slot);       // Here's the upreference
148
149  TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
150
151  std::string Result;
152  switch (Ty->getPrimitiveID()) {
153  case Type::FunctionTyID: {
154    const FunctionType *FTy = cast<FunctionType>(Ty);
155    Result = calcTypeName(FTy->getReturnType(), TypeStack, TypeNames) + " (";
156    for (FunctionType::ParamTypes::const_iterator
157           I = FTy->getParamTypes().begin(),
158           E = FTy->getParamTypes().end(); I != E; ++I) {
159      if (I != FTy->getParamTypes().begin())
160        Result += ", ";
161      Result += calcTypeName(*I, TypeStack, TypeNames);
162    }
163    if (FTy->isVarArg()) {
164      if (!FTy->getParamTypes().empty()) Result += ", ";
165      Result += "...";
166    }
167    Result += ")";
168    break;
169  }
170  case Type::StructTyID: {
171    const StructType *STy = cast<StructType>(Ty);
172    Result = "{ ";
173    for (StructType::ElementTypes::const_iterator
174           I = STy->getElementTypes().begin(),
175           E = STy->getElementTypes().end(); I != E; ++I) {
176      if (I != STy->getElementTypes().begin())
177        Result += ", ";
178      Result += calcTypeName(*I, TypeStack, TypeNames);
179    }
180    Result += " }";
181    break;
182  }
183  case Type::PointerTyID:
184    Result = calcTypeName(cast<PointerType>(Ty)->getElementType(),
185                          TypeStack, TypeNames) + "*";
186    break;
187  case Type::ArrayTyID: {
188    const ArrayType *ATy = cast<ArrayType>(Ty);
189    Result = "[" + utostr(ATy->getNumElements()) + " x ";
190    Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
191    break;
192  }
193  case Type::OpaqueTyID:
194    Result = "opaque";
195    break;
196  default:
197    Result = "<unrecognized-type>";
198  }
199
200  TypeStack.pop_back();       // Remove self from stack...
201  return Result;
202}
203
204
205// printTypeInt - The internal guts of printing out a type that has a
206// potentially named portion.
207//
208static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
209                              std::map<const Type *, std::string> &TypeNames) {
210  // Primitive types always print out their description, regardless of whether
211  // they have been named or not.
212  //
213  if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
214    return Out << Ty->getDescription();
215
216  // Check to see if the type is named.
217  std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
218  if (I != TypeNames.end()) return Out << I->second;
219
220  // Otherwise we have a type that has not been named but is a derived type.
221  // Carefully recurse the type hierarchy to print out any contained symbolic
222  // names.
223  //
224  std::vector<const Type *> TypeStack;
225  std::string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
226  TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
227  return Out << TypeName;
228}
229
230
231// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
232// type, iff there is an entry in the modules symbol table for the specified
233// type or one of it's component types.  This is slower than a simple x << Type;
234//
235std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
236                                      const Module *M) {
237  Out << " ";
238
239  // If they want us to print out a type, attempt to make it symbolic if there
240  // is a symbol table in the module...
241  if (M) {
242    std::map<const Type *, std::string> TypeNames;
243    fillTypeNameTable(M, TypeNames);
244
245    return printTypeInt(Out, Ty, TypeNames);
246  } else {
247    return Out << Ty->getDescription();
248  }
249}
250
251static void WriteConstantInt(std::ostream &Out, const Constant *CV,
252                             bool PrintName,
253                             std::map<const Type *, std::string> &TypeTable,
254                             SlotCalculator *Table) {
255  if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
256    Out << (CB == ConstantBool::True ? "true" : "false");
257  } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
258    Out << CI->getValue();
259  } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
260    Out << CI->getValue();
261  } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
262    // We would like to output the FP constant value in exponential notation,
263    // but we cannot do this if doing so will lose precision.  Check here to
264    // make sure that we only output it in exponential format if we can parse
265    // the value back and get the same value.
266    //
267    std::string StrVal = ftostr(CFP->getValue());
268
269    // Check to make sure that the stringized number is not some string like
270    // "Inf" or NaN, that atof will accept, but the lexer will not.  Check that
271    // the string matches the "[-+]?[0-9]" regex.
272    //
273    if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
274        ((StrVal[0] == '-' || StrVal[0] == '+') &&
275         (StrVal[1] >= '0' && StrVal[1] <= '9')))
276      // Reparse stringized version!
277      if (atof(StrVal.c_str()) == CFP->getValue()) {
278        Out << StrVal; return;
279      }
280
281    // Otherwise we could not reparse it to exactly the same value, so we must
282    // output the string in hexadecimal format!
283    //
284    // Behave nicely in the face of C TBAA rules... see:
285    // http://www.nullstone.com/htmls/category/aliastyp.htm
286    //
287    double Val = CFP->getValue();
288    char *Ptr = (char*)&Val;
289    assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
290           "assuming that double is 64 bits!");
291    Out << "0x" << utohexstr(*(uint64_t*)Ptr);
292
293  } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
294    if (CA->getNumOperands() > 5 && CA->isNullValue()) {
295      Out << "zeroinitializer";
296      return;
297    }
298
299    // As a special case, print the array as a string if it is an array of
300    // ubytes or an array of sbytes with positive values.
301    //
302    const Type *ETy = CA->getType()->getElementType();
303    bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
304
305    if (ETy == Type::SByteTy)
306      for (unsigned i = 0; i < CA->getNumOperands(); ++i)
307        if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
308          isString = false;
309          break;
310        }
311
312    if (isString) {
313      Out << "c\"";
314      for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
315        unsigned char C = cast<ConstantInt>(CA->getOperand(i))->getRawValue();
316
317        if (isprint(C) && C != '"' && C != '\\') {
318          Out << C;
319        } else {
320          Out << '\\'
321              << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
322              << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
323        }
324      }
325      Out << "\"";
326
327    } else {                // Cannot output in string format...
328      Out << "[";
329      if (CA->getNumOperands()) {
330        Out << " ";
331        printTypeInt(Out, ETy, TypeTable);
332        WriteAsOperandInternal(Out, CA->getOperand(0),
333                               PrintName, TypeTable, Table);
334        for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
335          Out << ", ";
336          printTypeInt(Out, ETy, TypeTable);
337          WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
338                                 TypeTable, Table);
339        }
340      }
341      Out << " ]";
342    }
343  } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
344    if (CS->getNumOperands() > 5 && CS->isNullValue()) {
345      Out << "zeroinitializer";
346      return;
347    }
348
349    Out << "{";
350    if (CS->getNumOperands()) {
351      Out << " ";
352      printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
353
354      WriteAsOperandInternal(Out, CS->getOperand(0),
355                             PrintName, TypeTable, Table);
356
357      for (unsigned i = 1; i < CS->getNumOperands(); i++) {
358        Out << ", ";
359        printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
360
361        WriteAsOperandInternal(Out, CS->getOperand(i),
362                               PrintName, TypeTable, Table);
363      }
364    }
365
366    Out << " }";
367  } else if (isa<ConstantPointerNull>(CV)) {
368    Out << "null";
369
370  } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
371    const GlobalValue *V = PR->getValue();
372    if (V->hasName()) {
373      Out << getLLVMName(V->getName());
374    } else if (Table) {
375      int Slot = Table->getSlot(V);
376      if (Slot >= 0)
377        Out << "%" << Slot;
378      else
379        Out << "<pointer reference badref>";
380    } else {
381      Out << "<pointer reference without context info>";
382    }
383
384  } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
385    Out << CE->getOpcodeName() << " (";
386
387    for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
388      printTypeInt(Out, (*OI)->getType(), TypeTable);
389      WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Table);
390      if (OI+1 != CE->op_end())
391        Out << ", ";
392    }
393
394    if (CE->getOpcode() == Instruction::Cast) {
395      Out << " to ";
396      printTypeInt(Out, CE->getType(), TypeTable);
397    }
398    Out << ")";
399
400  } else {
401    Out << "<placeholder or erroneous Constant>";
402  }
403}
404
405
406// WriteAsOperand - Write the name of the specified value out to the specified
407// ostream.  This can be useful when you just want to print int %reg126, not the
408// whole instruction that generated it.
409//
410static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
411                                   bool PrintName,
412                                  std::map<const Type*, std::string> &TypeTable,
413                                   SlotCalculator *Table) {
414  Out << " ";
415  if (PrintName && V->hasName()) {
416    Out << getLLVMName(V->getName());
417  } else {
418    if (const Constant *CV = dyn_cast<Constant>(V)) {
419      WriteConstantInt(Out, CV, PrintName, TypeTable, Table);
420    } else {
421      int Slot;
422      if (Table) {
423	Slot = Table->getSlot(V);
424      } else {
425        if (const Type *Ty = dyn_cast<Type>(V)) {
426          Out << Ty->getDescription();
427          return;
428        }
429
430        Table = createSlotCalculator(V);
431        if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
432
433	Slot = Table->getSlot(V);
434	delete Table;
435      }
436      if (Slot >= 0)  Out << "%" << Slot;
437      else if (PrintName)
438        Out << "<badref>";     // Not embedded into a location?
439    }
440  }
441}
442
443
444
445// WriteAsOperand - Write the name of the specified value out to the specified
446// ostream.  This can be useful when you just want to print int %reg126, not the
447// whole instruction that generated it.
448//
449std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
450                                   bool PrintType,
451                             bool PrintName, const Module *Context) {
452  std::map<const Type *, std::string> TypeNames;
453  if (Context == 0) Context = getModuleFromVal(V);
454
455  if (Context)
456    fillTypeNameTable(Context, TypeNames);
457
458  if (PrintType)
459    printTypeInt(Out, V->getType(), TypeNames);
460
461  if (const Type *Ty = dyn_cast<Type> (V))
462    printTypeInt(Out, Ty, TypeNames);
463
464  WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
465  return Out;
466}
467
468namespace llvm {
469
470class AssemblyWriter {
471  std::ostream &Out;
472  SlotCalculator &Table;
473  const Module *TheModule;
474  std::map<const Type *, std::string> TypeNames;
475  AssemblyAnnotationWriter *AnnotationWriter;
476public:
477  inline AssemblyWriter(std::ostream &o, SlotCalculator &Tab, const Module *M,
478                        AssemblyAnnotationWriter *AAW)
479    : Out(o), Table(Tab), TheModule(M), AnnotationWriter(AAW) {
480
481    // If the module has a symbol table, take all global types and stuff their
482    // names into the TypeNames map.
483    //
484    fillTypeNameTable(M, TypeNames);
485  }
486
487  inline void write(const Module *M)         { printModule(M);      }
488  inline void write(const GlobalVariable *G) { printGlobal(G);      }
489  inline void write(const Function *F)       { printFunction(F);    }
490  inline void write(const BasicBlock *BB)    { printBasicBlock(BB); }
491  inline void write(const Instruction *I)    { printInstruction(*I); }
492  inline void write(const Constant *CPV)     { printConstant(CPV);  }
493  inline void write(const Type *Ty)          { printType(Ty);       }
494
495  void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
496
497private :
498  void printModule(const Module *M);
499  void printSymbolTable(const SymbolTable &ST);
500  void printConstant(const Constant *CPV);
501  void printGlobal(const GlobalVariable *GV);
502  void printFunction(const Function *F);
503  void printArgument(const Argument *FA);
504  void printBasicBlock(const BasicBlock *BB);
505  void printInstruction(const Instruction &I);
506
507  // printType - Go to extreme measures to attempt to print out a short,
508  // symbolic version of a type name.
509  //
510  std::ostream &printType(const Type *Ty) {
511    return printTypeInt(Out, Ty, TypeNames);
512  }
513
514  // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
515  // without considering any symbolic types that we may have equal to it.
516  //
517  std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
518
519  // printInfoComment - Print a little comment after the instruction indicating
520  // which slot it occupies.
521  void printInfoComment(const Value &V);
522};
523}  // end of anonymous namespace
524
525// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
526// without considering any symbolic types that we may have equal to it.
527//
528std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
529  if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
530    printType(FTy->getReturnType()) << " (";
531    for (FunctionType::ParamTypes::const_iterator
532           I = FTy->getParamTypes().begin(),
533           E = FTy->getParamTypes().end(); I != E; ++I) {
534      if (I != FTy->getParamTypes().begin())
535        Out << ", ";
536      printType(*I);
537    }
538    if (FTy->isVarArg()) {
539      if (!FTy->getParamTypes().empty()) Out << ", ";
540      Out << "...";
541    }
542    Out << ")";
543  } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
544    Out << "{ ";
545    for (StructType::ElementTypes::const_iterator
546           I = STy->getElementTypes().begin(),
547           E = STy->getElementTypes().end(); I != E; ++I) {
548      if (I != STy->getElementTypes().begin())
549        Out << ", ";
550      printType(*I);
551    }
552    Out << " }";
553  } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
554    printType(PTy->getElementType()) << "*";
555  } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
556    Out << "[" << ATy->getNumElements() << " x ";
557    printType(ATy->getElementType()) << "]";
558  } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
559    Out << "opaque";
560  } else {
561    if (!Ty->isPrimitiveType())
562      Out << "<unknown derived type>";
563    printType(Ty);
564  }
565  return Out;
566}
567
568
569void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
570				  bool PrintName) {
571  if (PrintType) { Out << " "; printType(Operand->getType()); }
572  WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Table);
573}
574
575
576void AssemblyWriter::printModule(const Module *M) {
577  switch (M->getEndianness()) {
578  case Module::LittleEndian: Out << "target endian = little\n"; break;
579  case Module::BigEndian:    Out << "target endian = big\n";    break;
580  case Module::AnyEndianness: break;
581  }
582  switch (M->getPointerSize()) {
583  case Module::Pointer32:    Out << "target pointersize = 32\n"; break;
584  case Module::Pointer64:    Out << "target pointersize = 64\n"; break;
585  case Module::AnyPointerSize: break;
586  }
587
588  // Loop over the symbol table, emitting all named constants...
589  printSymbolTable(M->getSymbolTable());
590
591  for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
592    printGlobal(I);
593
594  Out << "\nimplementation   ; Functions:\n";
595
596  // Output all of the functions...
597  for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
598    printFunction(I);
599}
600
601void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
602  if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
603
604  if (!GV->hasInitializer())
605    Out << "external ";
606  else
607    switch (GV->getLinkage()) {
608    case GlobalValue::InternalLinkage:  Out << "internal "; break;
609    case GlobalValue::LinkOnceLinkage:  Out << "linkonce "; break;
610    case GlobalValue::WeakLinkage:      Out << "weak "; break;
611    case GlobalValue::AppendingLinkage: Out << "appending "; break;
612    case GlobalValue::ExternalLinkage: break;
613    }
614
615  Out << (GV->isConstant() ? "constant " : "global ");
616  printType(GV->getType()->getElementType());
617
618  if (GV->hasInitializer())
619    writeOperand(GV->getInitializer(), false, false);
620
621  printInfoComment(*GV);
622  Out << "\n";
623}
624
625
626// printSymbolTable - Run through symbol table looking for named constants
627// if a named constant is found, emit it's declaration...
628//
629void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
630  for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
631    SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
632    SymbolTable::type_const_iterator End = ST.type_end(TI->first);
633
634    for (; I != End; ++I) {
635      const Value *V = I->second;
636      if (const Constant *CPV = dyn_cast<Constant>(V)) {
637	printConstant(CPV);
638      } else if (const Type *Ty = dyn_cast<Type>(V)) {
639        assert(Ty->getType() == Type::TypeTy && TI->first == Type::TypeTy);
640	Out << "\t" << getLLVMName(I->first) << " = type ";
641
642        // Make sure we print out at least one level of the type structure, so
643        // that we do not get %FILE = type %FILE
644        //
645        printTypeAtLeastOneLevel(Ty) << "\n";
646      }
647    }
648  }
649}
650
651
652// printConstant - Print out a constant pool entry...
653//
654void AssemblyWriter::printConstant(const Constant *CPV) {
655  // Don't print out unnamed constants, they will be inlined
656  if (!CPV->hasName()) return;
657
658  // Print out name...
659  Out << "\t" << getLLVMName(CPV->getName()) << " =";
660
661  // Write the value out now...
662  writeOperand(CPV, true, false);
663
664  printInfoComment(*CPV);
665  Out << "\n";
666}
667
668// printFunction - Print all aspects of a function.
669//
670void AssemblyWriter::printFunction(const Function *F) {
671  // Print out the return type and name...
672  Out << "\n";
673
674  if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
675
676  if (F->isExternal())
677    Out << "declare ";
678  else
679    switch (F->getLinkage()) {
680    case GlobalValue::InternalLinkage:  Out << "internal "; break;
681    case GlobalValue::LinkOnceLinkage:  Out << "linkonce "; break;
682    case GlobalValue::WeakLinkage:      Out << "weak "; break;
683    case GlobalValue::AppendingLinkage: Out << "appending "; break;
684    case GlobalValue::ExternalLinkage: break;
685    }
686
687  printType(F->getReturnType()) << " ";
688  if (!F->getName().empty())
689    Out << getLLVMName(F->getName());
690  else
691    Out << "\"\"";
692  Out << "(";
693  Table.incorporateFunction(F);
694
695  // Loop over the arguments, printing them...
696  const FunctionType *FT = F->getFunctionType();
697
698  for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
699    printArgument(I);
700
701  // Finish printing arguments...
702  if (FT->isVarArg()) {
703    if (FT->getParamTypes().size()) Out << ", ";
704    Out << "...";  // Output varargs portion of signature!
705  }
706  Out << ")";
707
708  if (F->isExternal()) {
709    Out << "\n";
710  } else {
711    Out << " {";
712
713    // Output all of its basic blocks... for the function
714    for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
715      printBasicBlock(I);
716
717    Out << "}\n";
718  }
719
720  Table.purgeFunction();
721}
722
723// printArgument - This member is called for every argument that
724// is passed into the function.  Simply print it out
725//
726void AssemblyWriter::printArgument(const Argument *Arg) {
727  // Insert commas as we go... the first arg doesn't get a comma
728  if (Arg != &Arg->getParent()->afront()) Out << ", ";
729
730  // Output type...
731  printType(Arg->getType());
732
733  // Output name, if available...
734  if (Arg->hasName())
735    Out << " " << getLLVMName(Arg->getName());
736  else if (Table.getSlot(Arg) < 0)
737    Out << "<badref>";
738}
739
740// printBasicBlock - This member is called for each basic block in a method.
741//
742void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
743  if (BB->hasName()) {              // Print out the label if it exists...
744    Out << "\n" << BB->getName() << ":";
745  } else if (!BB->use_empty()) {      // Don't print block # of no uses...
746    int Slot = Table.getSlot(BB);
747    Out << "\n; <label>:";
748    if (Slot >= 0)
749      Out << Slot;         // Extra newline separates out label's
750    else
751      Out << "<badref>";
752  }
753
754  if (BB->getParent() == 0)
755    Out << "\t\t; Error: Block without parent!";
756  else {
757    if (BB != &BB->getParent()->front()) {  // Not the entry block?
758      // Output predecessors for the block...
759      Out << "\t\t;";
760      pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
761
762      if (PI == PE) {
763        Out << " No predecessors!";
764      } else {
765        Out << " preds =";
766        writeOperand(*PI, false, true);
767        for (++PI; PI != PE; ++PI) {
768          Out << ",";
769          writeOperand(*PI, false, true);
770        }
771      }
772    }
773  }
774
775  Out << "\n";
776
777  if (AnnotationWriter) AnnotationWriter->emitBasicBlockAnnot(BB, Out);
778
779  // Output all of the instructions in the basic block...
780  for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
781    printInstruction(*I);
782}
783
784
785// printInfoComment - Print a little comment after the instruction indicating
786// which slot it occupies.
787//
788void AssemblyWriter::printInfoComment(const Value &V) {
789  if (V.getType() != Type::VoidTy) {
790    Out << "\t\t; <";
791    printType(V.getType()) << ">";
792
793    if (!V.hasName()) {
794      int Slot = Table.getSlot(&V); // Print out the def slot taken...
795      if (Slot >= 0) Out << ":" << Slot;
796      else Out << ":<badref>";
797    }
798    Out << " [#uses=" << V.use_size() << "]";  // Output # uses
799  }
800}
801
802// printInstruction - This member is called for each Instruction in a method.
803//
804void AssemblyWriter::printInstruction(const Instruction &I) {
805  if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
806
807  Out << "\t";
808
809  // Print out name if it exists...
810  if (I.hasName())
811    Out << getLLVMName(I.getName()) << " = ";
812
813  // If this is a volatile load or store, print out the volatile marker
814  if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
815      (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
816      Out << "volatile ";
817
818  // Print out the opcode...
819  Out << I.getOpcodeName();
820
821  // Print out the type of the operands...
822  const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
823
824  // Special case conditional branches to swizzle the condition out to the front
825  if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
826    writeOperand(I.getOperand(2), true);
827    Out << ",";
828    writeOperand(Operand, true);
829    Out << ",";
830    writeOperand(I.getOperand(1), true);
831
832  } else if (isa<SwitchInst>(I)) {
833    // Special case switch statement to get formatting nice and correct...
834    writeOperand(Operand        , true); Out << ",";
835    writeOperand(I.getOperand(1), true); Out << " [";
836
837    for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
838      Out << "\n\t\t";
839      writeOperand(I.getOperand(op  ), true); Out << ",";
840      writeOperand(I.getOperand(op+1), true);
841    }
842    Out << "\n\t]";
843  } else if (isa<PHINode>(I)) {
844    Out << " ";
845    printType(I.getType());
846    Out << " ";
847
848    for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
849      if (op) Out << ", ";
850      Out << "[";
851      writeOperand(I.getOperand(op  ), false); Out << ",";
852      writeOperand(I.getOperand(op+1), false); Out << " ]";
853    }
854  } else if (isa<ReturnInst>(I) && !Operand) {
855    Out << " void";
856  } else if (isa<CallInst>(I)) {
857    const PointerType  *PTy = cast<PointerType>(Operand->getType());
858    const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
859    const Type       *RetTy = FTy->getReturnType();
860
861    // If possible, print out the short form of the call instruction.  We can
862    // only do this if the first argument is a pointer to a nonvararg function,
863    // and if the return type is not a pointer to a function.
864    //
865    if (!FTy->isVarArg() &&
866        (!isa<PointerType>(RetTy) ||
867         !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
868      Out << " "; printType(RetTy);
869      writeOperand(Operand, false);
870    } else {
871      writeOperand(Operand, true);
872    }
873    Out << "(";
874    if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
875    for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
876      Out << ",";
877      writeOperand(I.getOperand(op), true);
878    }
879
880    Out << " )";
881  } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
882    const PointerType  *PTy = cast<PointerType>(Operand->getType());
883    const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
884    const Type       *RetTy = FTy->getReturnType();
885
886    // If possible, print out the short form of the invoke instruction. We can
887    // only do this if the first argument is a pointer to a nonvararg function,
888    // and if the return type is not a pointer to a function.
889    //
890    if (!FTy->isVarArg() &&
891        (!isa<PointerType>(RetTy) ||
892         !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
893      Out << " "; printType(RetTy);
894      writeOperand(Operand, false);
895    } else {
896      writeOperand(Operand, true);
897    }
898
899    Out << "(";
900    if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
901    for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
902      Out << ",";
903      writeOperand(I.getOperand(op), true);
904    }
905
906    Out << " )\n\t\t\tto";
907    writeOperand(II->getNormalDest(), true);
908    Out << " except";
909    writeOperand(II->getExceptionalDest(), true);
910
911  } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
912    Out << " ";
913    printType(AI->getType()->getElementType());
914    if (AI->isArrayAllocation()) {
915      Out << ",";
916      writeOperand(AI->getArraySize(), true);
917    }
918  } else if (isa<CastInst>(I)) {
919    if (Operand) writeOperand(Operand, true);   // Work with broken code
920    Out << " to ";
921    printType(I.getType());
922  } else if (isa<VAArgInst>(I)) {
923    if (Operand) writeOperand(Operand, true);   // Work with broken code
924    Out << ", ";
925    printType(I.getType());
926  } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
927    if (Operand) writeOperand(Operand, true);   // Work with broken code
928    Out << ", ";
929    printType(VAN->getArgType());
930  } else if (Operand) {   // Print the normal way...
931
932    // PrintAllTypes - Instructions who have operands of all the same type
933    // omit the type from all but the first operand.  If the instruction has
934    // different type operands (for example br), then they are all printed.
935    bool PrintAllTypes = false;
936    const Type *TheType = Operand->getType();
937
938    // Shift Left & Right print both types even for Ubyte LHS
939    if (isa<ShiftInst>(I)) {
940      PrintAllTypes = true;
941    } else {
942      for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
943        Operand = I.getOperand(i);
944        if (Operand->getType() != TheType) {
945          PrintAllTypes = true;    // We have differing types!  Print them all!
946          break;
947        }
948      }
949    }
950
951    if (!PrintAllTypes) {
952      Out << " ";
953      printType(TheType);
954    }
955
956    for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
957      if (i) Out << ",";
958      writeOperand(I.getOperand(i), PrintAllTypes);
959    }
960  }
961
962  printInfoComment(I);
963  Out << "\n";
964}
965
966
967//===----------------------------------------------------------------------===//
968//                       External Interface declarations
969//===----------------------------------------------------------------------===//
970
971void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
972  SlotCalculator SlotTable(this, true);
973  AssemblyWriter W(o, SlotTable, this, AAW);
974  W.write(this);
975}
976
977void GlobalVariable::print(std::ostream &o) const {
978  SlotCalculator SlotTable(getParent(), true);
979  AssemblyWriter W(o, SlotTable, getParent(), 0);
980  W.write(this);
981}
982
983void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
984  SlotCalculator SlotTable(getParent(), true);
985  AssemblyWriter W(o, SlotTable, getParent(), AAW);
986
987  W.write(this);
988}
989
990void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
991  SlotCalculator SlotTable(getParent(), true);
992  AssemblyWriter W(o, SlotTable,
993                   getParent() ? getParent()->getParent() : 0, AAW);
994  W.write(this);
995}
996
997void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
998  const Function *F = getParent() ? getParent()->getParent() : 0;
999  SlotCalculator SlotTable(F, true);
1000  AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1001
1002  W.write(this);
1003}
1004
1005void Constant::print(std::ostream &o) const {
1006  if (this == 0) { o << "<null> constant value\n"; return; }
1007
1008  // Handle CPR's special, because they have context information...
1009  if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
1010    CPR->getValue()->print(o);  // Print as a global value, with context info.
1011    return;
1012  }
1013
1014  o << " " << getType()->getDescription() << " ";
1015
1016  std::map<const Type *, std::string> TypeTable;
1017  WriteConstantInt(o, this, false, TypeTable, 0);
1018}
1019
1020void Type::print(std::ostream &o) const {
1021  if (this == 0)
1022    o << "<null Type>";
1023  else
1024    o << getDescription();
1025}
1026
1027void Argument::print(std::ostream &o) const {
1028  o << getType() << " " << getName();
1029}
1030
1031void Value::dump() const { print(std::cerr); }
1032
1033//===----------------------------------------------------------------------===//
1034//  CachedWriter Class Implementation
1035//===----------------------------------------------------------------------===//
1036
1037void CachedWriter::setModule(const Module *M) {
1038  delete SC; delete AW;
1039  if (M) {
1040    SC = new SlotCalculator(M, true);
1041    AW = new AssemblyWriter(Out, *SC, M, 0);
1042  } else {
1043    SC = 0; AW = 0;
1044  }
1045}
1046
1047CachedWriter::~CachedWriter() {
1048  delete AW;
1049  delete SC;
1050}
1051
1052CachedWriter &CachedWriter::operator<<(const Value *V) {
1053  assert(AW && SC && "CachedWriter does not have a current module!");
1054  switch (V->getValueType()) {
1055  case Value::ConstantVal:
1056  case Value::ArgumentVal:       AW->writeOperand(V, true, true); break;
1057  case Value::TypeVal:           AW->write(cast<Type>(V)); break;
1058  case Value::InstructionVal:    AW->write(cast<Instruction>(V)); break;
1059  case Value::BasicBlockVal:     AW->write(cast<BasicBlock>(V)); break;
1060  case Value::FunctionVal:       AW->write(cast<Function>(V)); break;
1061  case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
1062  default: Out << "<unknown value type: " << V->getValueType() << ">"; break;
1063  }
1064  return *this;
1065}
1066