Remove dead test: this was already checked and handled a few lines
[oota-llvm.git] / lib / Target / CppBackend / CPPBackend.cpp
1 //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the writing of the LLVM IR as a set of C++ calls to the
11 // LLVM IR interface. The input module is assumed to be verified.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "CPPTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instruction.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/PassManager.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Config/config.h"
35 #include <algorithm>
36 #include <set>
37 #include <map>
38 using namespace llvm;
39
40 static cl::opt<std::string>
41 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
42          cl::value_desc("function name"));
43
44 enum WhatToGenerate {
45   GenProgram,
46   GenModule,
47   GenContents,
48   GenFunction,
49   GenFunctions,
50   GenInline,
51   GenVariable,
52   GenType
53 };
54
55 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
56   cl::desc("Choose what kind of output to generate"),
57   cl::init(GenProgram),
58   cl::values(
59     clEnumValN(GenProgram,  "program",   "Generate a complete program"),
60     clEnumValN(GenModule,   "module",    "Generate a module definition"),
61     clEnumValN(GenContents, "contents",  "Generate contents of a module"),
62     clEnumValN(GenFunction, "function",  "Generate a function definition"),
63     clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
64     clEnumValN(GenInline,   "inline",    "Generate an inline function"),
65     clEnumValN(GenVariable, "variable",  "Generate a variable definition"),
66     clEnumValN(GenType,     "type",      "Generate a type definition"),
67     clEnumValEnd
68   )
69 );
70
71 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
72   cl::desc("Specify the name of the thing to generate"),
73   cl::init("!bad!"));
74
75 extern "C" void LLVMInitializeCppBackendTarget() {
76   // Register the target.
77   RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
78 }
79
80 namespace {
81   typedef std::vector<Type*> TypeList;
82   typedef std::map<Type*,std::string> TypeMap;
83   typedef std::map<const Value*,std::string> ValueMap;
84   typedef std::set<std::string> NameSet;
85   typedef std::set<Type*> TypeSet;
86   typedef std::set<const Value*> ValueSet;
87   typedef std::map<const Value*,std::string> ForwardRefMap;
88
89   /// CppWriter - This class is the main chunk of code that converts an LLVM
90   /// module to a C++ translation unit.
91   class CppWriter : public ModulePass {
92     formatted_raw_ostream &Out;
93     const Module *TheModule;
94     uint64_t uniqueNum;
95     TypeMap TypeNames;
96     ValueMap ValueNames;
97     NameSet UsedNames;
98     TypeSet DefinedTypes;
99     ValueSet DefinedValues;
100     ForwardRefMap ForwardRefs;
101     bool is_inline;
102     unsigned indent_level;
103
104   public:
105     static char ID;
106     explicit CppWriter(formatted_raw_ostream &o) :
107       ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
108
109     virtual const char *getPassName() const { return "C++ backend"; }
110
111     bool runOnModule(Module &M);
112
113     void printProgram(const std::string& fname, const std::string& modName );
114     void printModule(const std::string& fname, const std::string& modName );
115     void printContents(const std::string& fname, const std::string& modName );
116     void printFunction(const std::string& fname, const std::string& funcName );
117     void printFunctions();
118     void printInline(const std::string& fname, const std::string& funcName );
119     void printVariable(const std::string& fname, const std::string& varName );
120     void printType(const std::string& fname, const std::string& typeName );
121
122     void error(const std::string& msg);
123
124     
125     formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
126     inline void in() { indent_level++; }
127     inline void out() { if (indent_level >0) indent_level--; }
128     
129   private:
130     void printLinkageType(GlobalValue::LinkageTypes LT);
131     void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
132     void printCallingConv(CallingConv::ID cc);
133     void printEscapedString(const std::string& str);
134     void printCFP(const ConstantFP* CFP);
135
136     std::string getCppName(Type* val);
137     inline void printCppName(Type* val);
138
139     std::string getCppName(const Value* val);
140     inline void printCppName(const Value* val);
141
142     void printAttributes(const AttrListPtr &PAL, const std::string &name);
143     void printType(Type* Ty);
144     void printTypes(const Module* M);
145
146     void printConstant(const Constant *CPV);
147     void printConstants(const Module* M);
148
149     void printVariableUses(const GlobalVariable *GV);
150     void printVariableHead(const GlobalVariable *GV);
151     void printVariableBody(const GlobalVariable *GV);
152
153     void printFunctionUses(const Function *F);
154     void printFunctionHead(const Function *F);
155     void printFunctionBody(const Function *F);
156     void printInstruction(const Instruction *I, const std::string& bbname);
157     std::string getOpName(const Value*);
158
159     void printModuleBody();
160   };
161 } // end anonymous namespace.
162
163 formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
164   Out << '\n';
165   if (delta >= 0 || indent_level >= unsigned(-delta))
166     indent_level += delta;
167   Out.indent(indent_level);
168   return Out;
169 }
170
171 static inline void sanitize(std::string &str) {
172   for (size_t i = 0; i < str.length(); ++i)
173     if (!isalnum(str[i]) && str[i] != '_')
174       str[i] = '_';
175 }
176
177 static std::string getTypePrefix(Type *Ty) {
178   switch (Ty->getTypeID()) {
179   case Type::VoidTyID:     return "void_";
180   case Type::IntegerTyID:
181     return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
182   case Type::FloatTyID:    return "float_";
183   case Type::DoubleTyID:   return "double_";
184   case Type::LabelTyID:    return "label_";
185   case Type::FunctionTyID: return "func_";
186   case Type::StructTyID:   return "struct_";
187   case Type::ArrayTyID:    return "array_";
188   case Type::PointerTyID:  return "ptr_";
189   case Type::VectorTyID:   return "packed_";
190   default:                 return "other_";
191   }
192 }
193
194 void CppWriter::error(const std::string& msg) {
195   report_fatal_error(msg);
196 }
197
198 // printCFP - Print a floating point constant .. very carefully :)
199 // This makes sure that conversion to/from floating yields the same binary
200 // result so that we don't lose precision.
201 void CppWriter::printCFP(const ConstantFP *CFP) {
202   bool ignored;
203   APFloat APF = APFloat(CFP->getValueAPF());  // copy
204   if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
205     APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
206   Out << "ConstantFP::get(mod->getContext(), ";
207   Out << "APFloat(";
208 #if HAVE_PRINTF_A
209   char Buffer[100];
210   sprintf(Buffer, "%A", APF.convertToDouble());
211   if ((!strncmp(Buffer, "0x", 2) ||
212        !strncmp(Buffer, "-0x", 3) ||
213        !strncmp(Buffer, "+0x", 3)) &&
214       APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
215     if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
216       Out << "BitsToDouble(" << Buffer << ")";
217     else
218       Out << "BitsToFloat((float)" << Buffer << ")";
219     Out << ")";
220   } else {
221 #endif
222     std::string StrVal = ftostr(CFP->getValueAPF());
223
224     while (StrVal[0] == ' ')
225       StrVal.erase(StrVal.begin());
226
227     // Check to make sure that the stringized number is not some string like
228     // "Inf" or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
229     if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
230          ((StrVal[0] == '-' || StrVal[0] == '+') &&
231           (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
232         (CFP->isExactlyValue(atof(StrVal.c_str())))) {
233       if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
234         Out <<  StrVal;
235       else
236         Out << StrVal << "f";
237     } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
238       Out << "BitsToDouble(0x"
239           << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
240           << "ULL) /* " << StrVal << " */";
241     else
242       Out << "BitsToFloat(0x"
243           << utohexstr((uint32_t)CFP->getValueAPF().
244                                       bitcastToAPInt().getZExtValue())
245           << "U) /* " << StrVal << " */";
246     Out << ")";
247 #if HAVE_PRINTF_A
248   }
249 #endif
250   Out << ")";
251 }
252
253 void CppWriter::printCallingConv(CallingConv::ID cc){
254   // Print the calling convention.
255   switch (cc) {
256   case CallingConv::C:     Out << "CallingConv::C"; break;
257   case CallingConv::Fast:  Out << "CallingConv::Fast"; break;
258   case CallingConv::Cold:  Out << "CallingConv::Cold"; break;
259   case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
260   default:                 Out << cc; break;
261   }
262 }
263
264 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
265   switch (LT) {
266   case GlobalValue::InternalLinkage:
267     Out << "GlobalValue::InternalLinkage"; break;
268   case GlobalValue::PrivateLinkage:
269     Out << "GlobalValue::PrivateLinkage"; break;
270   case GlobalValue::LinkerPrivateLinkage:
271     Out << "GlobalValue::LinkerPrivateLinkage"; break;
272   case GlobalValue::LinkerPrivateWeakLinkage:
273     Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
274   case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
275     Out << "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break;
276   case GlobalValue::AvailableExternallyLinkage:
277     Out << "GlobalValue::AvailableExternallyLinkage "; break;
278   case GlobalValue::LinkOnceAnyLinkage:
279     Out << "GlobalValue::LinkOnceAnyLinkage "; break;
280   case GlobalValue::LinkOnceODRLinkage:
281     Out << "GlobalValue::LinkOnceODRLinkage "; break;
282   case GlobalValue::WeakAnyLinkage:
283     Out << "GlobalValue::WeakAnyLinkage"; break;
284   case GlobalValue::WeakODRLinkage:
285     Out << "GlobalValue::WeakODRLinkage"; break;
286   case GlobalValue::AppendingLinkage:
287     Out << "GlobalValue::AppendingLinkage"; break;
288   case GlobalValue::ExternalLinkage:
289     Out << "GlobalValue::ExternalLinkage"; break;
290   case GlobalValue::DLLImportLinkage:
291     Out << "GlobalValue::DLLImportLinkage"; break;
292   case GlobalValue::DLLExportLinkage:
293     Out << "GlobalValue::DLLExportLinkage"; break;
294   case GlobalValue::ExternalWeakLinkage:
295     Out << "GlobalValue::ExternalWeakLinkage"; break;
296   case GlobalValue::CommonLinkage:
297     Out << "GlobalValue::CommonLinkage"; break;
298   }
299 }
300
301 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
302   switch (VisType) {
303   case GlobalValue::DefaultVisibility:
304     Out << "GlobalValue::DefaultVisibility";
305     break;
306   case GlobalValue::HiddenVisibility:
307     Out << "GlobalValue::HiddenVisibility";
308     break;
309   case GlobalValue::ProtectedVisibility:
310     Out << "GlobalValue::ProtectedVisibility";
311     break;
312   }
313 }
314
315 // printEscapedString - Print each character of the specified string, escaping
316 // it if it is not printable or if it is an escape char.
317 void CppWriter::printEscapedString(const std::string &Str) {
318   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
319     unsigned char C = Str[i];
320     if (isprint(C) && C != '"' && C != '\\') {
321       Out << C;
322     } else {
323       Out << "\\x"
324           << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
325           << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
326     }
327   }
328 }
329
330 std::string CppWriter::getCppName(Type* Ty) {
331   // First, handle the primitive types .. easy
332   if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
333     switch (Ty->getTypeID()) {
334     case Type::VoidTyID:   return "Type::getVoidTy(mod->getContext())";
335     case Type::IntegerTyID: {
336       unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
337       return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
338     }
339     case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
340     case Type::FloatTyID:    return "Type::getFloatTy(mod->getContext())";
341     case Type::DoubleTyID:   return "Type::getDoubleTy(mod->getContext())";
342     case Type::LabelTyID:    return "Type::getLabelTy(mod->getContext())";
343     case Type::X86_MMXTyID:  return "Type::getX86_MMXTy(mod->getContext())";
344     default:
345       error("Invalid primitive type");
346       break;
347     }
348     // shouldn't be returned, but make it sensible
349     return "Type::getVoidTy(mod->getContext())";
350   }
351
352   // Now, see if we've seen the type before and return that
353   TypeMap::iterator I = TypeNames.find(Ty);
354   if (I != TypeNames.end())
355     return I->second;
356
357   // Okay, let's build a new name for this type. Start with a prefix
358   const char* prefix = 0;
359   switch (Ty->getTypeID()) {
360   case Type::FunctionTyID:    prefix = "FuncTy_"; break;
361   case Type::StructTyID:      prefix = "StructTy_"; break;
362   case Type::ArrayTyID:       prefix = "ArrayTy_"; break;
363   case Type::PointerTyID:     prefix = "PointerTy_"; break;
364   case Type::VectorTyID:      prefix = "VectorTy_"; break;
365   default:                    prefix = "OtherTy_"; break; // prevent breakage
366   }
367
368   // See if the type has a name in the symboltable and build accordingly
369   std::string name;
370   if (StructType *STy = dyn_cast<StructType>(Ty))
371     if (STy->hasName())
372       name = STy->getName();
373   
374   if (name.empty())
375     name = utostr(uniqueNum++);
376   
377   name = std::string(prefix) + name;
378   sanitize(name);
379
380   // Save the name
381   return TypeNames[Ty] = name;
382 }
383
384 void CppWriter::printCppName(Type* Ty) {
385   printEscapedString(getCppName(Ty));
386 }
387
388 std::string CppWriter::getCppName(const Value* val) {
389   std::string name;
390   ValueMap::iterator I = ValueNames.find(val);
391   if (I != ValueNames.end() && I->first == val)
392     return  I->second;
393
394   if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
395     name = std::string("gvar_") +
396       getTypePrefix(GV->getType()->getElementType());
397   } else if (isa<Function>(val)) {
398     name = std::string("func_");
399   } else if (const Constant* C = dyn_cast<Constant>(val)) {
400     name = std::string("const_") + getTypePrefix(C->getType());
401   } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
402     if (is_inline) {
403       unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
404                                       Function::const_arg_iterator(Arg)) + 1;
405       name = std::string("arg_") + utostr(argNum);
406       NameSet::iterator NI = UsedNames.find(name);
407       if (NI != UsedNames.end())
408         name += std::string("_") + utostr(uniqueNum++);
409       UsedNames.insert(name);
410       return ValueNames[val] = name;
411     } else {
412       name = getTypePrefix(val->getType());
413     }
414   } else {
415     name = getTypePrefix(val->getType());
416   }
417   if (val->hasName())
418     name += val->getName();
419   else
420     name += utostr(uniqueNum++);
421   sanitize(name);
422   NameSet::iterator NI = UsedNames.find(name);
423   if (NI != UsedNames.end())
424     name += std::string("_") + utostr(uniqueNum++);
425   UsedNames.insert(name);
426   return ValueNames[val] = name;
427 }
428
429 void CppWriter::printCppName(const Value* val) {
430   printEscapedString(getCppName(val));
431 }
432
433 void CppWriter::printAttributes(const AttrListPtr &PAL,
434                                 const std::string &name) {
435   Out << "AttrListPtr " << name << "_PAL;";
436   nl(Out);
437   if (!PAL.isEmpty()) {
438     Out << '{'; in(); nl(Out);
439     Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
440     Out << "AttributeWithIndex PAWI;"; nl(Out);
441     for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
442       unsigned index = PAL.getSlot(i).Index;
443       Attributes attrs = PAL.getSlot(i).Attrs;
444       Out << "PAWI.Index = " << index << "U; PAWI.Attrs = Attribute::None ";
445 #define HANDLE_ATTR(X)                 \
446       if (attrs & Attribute::X)      \
447         Out << " | Attribute::" #X;  \
448       attrs &= ~Attribute::X;
449       
450       HANDLE_ATTR(SExt);
451       HANDLE_ATTR(ZExt);
452       HANDLE_ATTR(NoReturn);
453       HANDLE_ATTR(InReg);
454       HANDLE_ATTR(StructRet);
455       HANDLE_ATTR(NoUnwind);
456       HANDLE_ATTR(NoAlias);
457       HANDLE_ATTR(ByVal);
458       HANDLE_ATTR(Nest);
459       HANDLE_ATTR(ReadNone);
460       HANDLE_ATTR(ReadOnly);
461       HANDLE_ATTR(NoInline);
462       HANDLE_ATTR(AlwaysInline);
463       HANDLE_ATTR(OptimizeForSize);
464       HANDLE_ATTR(StackProtect);
465       HANDLE_ATTR(StackProtectReq);
466       HANDLE_ATTR(NoCapture);
467       HANDLE_ATTR(NoRedZone);
468       HANDLE_ATTR(NoImplicitFloat);
469       HANDLE_ATTR(Naked);
470       HANDLE_ATTR(InlineHint);
471       HANDLE_ATTR(ReturnsTwice);
472       HANDLE_ATTR(UWTable);
473       HANDLE_ATTR(NonLazyBind);
474 #undef HANDLE_ATTR
475       if (attrs & Attribute::StackAlignment)
476         Out << " | Attribute::constructStackAlignmentFromInt("
477             << Attribute::getStackAlignmentFromAttrs(attrs)
478             << ")"; 
479       attrs &= ~Attribute::StackAlignment;
480       assert(attrs == 0 && "Unhandled attribute!");
481       Out << ";";
482       nl(Out);
483       Out << "Attrs.push_back(PAWI);";
484       nl(Out);
485     }
486     Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
487     nl(Out);
488     out(); nl(Out);
489     Out << '}'; nl(Out);
490   }
491 }
492
493 void CppWriter::printType(Type* Ty) {
494   // We don't print definitions for primitive types
495   if (Ty->isPrimitiveType() || Ty->isIntegerTy())
496     return;
497
498   // If we already defined this type, we don't need to define it again.
499   if (DefinedTypes.find(Ty) != DefinedTypes.end())
500     return;
501
502   // Everything below needs the name for the type so get it now.
503   std::string typeName(getCppName(Ty));
504
505   // Print the type definition
506   switch (Ty->getTypeID()) {
507   case Type::FunctionTyID:  {
508     FunctionType* FT = cast<FunctionType>(Ty);
509     Out << "std::vector<Type*>" << typeName << "_args;";
510     nl(Out);
511     FunctionType::param_iterator PI = FT->param_begin();
512     FunctionType::param_iterator PE = FT->param_end();
513     for (; PI != PE; ++PI) {
514       Type* argTy = static_cast<Type*>(*PI);
515       printType(argTy);
516       std::string argName(getCppName(argTy));
517       Out << typeName << "_args.push_back(" << argName;
518       Out << ");";
519       nl(Out);
520     }
521     printType(FT->getReturnType());
522     std::string retTypeName(getCppName(FT->getReturnType()));
523     Out << "FunctionType* " << typeName << " = FunctionType::get(";
524     in(); nl(Out) << "/*Result=*/" << retTypeName;
525     Out << ",";
526     nl(Out) << "/*Params=*/" << typeName << "_args,";
527     nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
528     out();
529     nl(Out);
530     break;
531   }
532   case Type::StructTyID: {
533     StructType* ST = cast<StructType>(Ty);
534     if (!ST->isLiteral()) {
535       Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
536       printEscapedString(ST->getName());
537       Out << "\");";
538       nl(Out);
539       Out << "if (!" << typeName << ") {";
540       nl(Out);
541       Out << typeName << " = ";
542       Out << "StructType::create(mod->getContext(), \"";
543       printEscapedString(ST->getName());
544       Out << "\");";
545       nl(Out);
546       Out << "}";
547       nl(Out);
548       // Indicate that this type is now defined.
549       DefinedTypes.insert(Ty);
550     }
551
552     Out << "std::vector<Type*>" << typeName << "_fields;";
553     nl(Out);
554     StructType::element_iterator EI = ST->element_begin();
555     StructType::element_iterator EE = ST->element_end();
556     for (; EI != EE; ++EI) {
557       Type* fieldTy = static_cast<Type*>(*EI);
558       printType(fieldTy);
559       std::string fieldName(getCppName(fieldTy));
560       Out << typeName << "_fields.push_back(" << fieldName;
561       Out << ");";
562       nl(Out);
563     }
564
565     if (ST->isLiteral()) {
566       Out << "StructType *" << typeName << " = ";
567       Out << "StructType::get(" << "mod->getContext(), ";
568     } else {
569       Out << "if (" << typeName << "->isOpaque()) {";
570       nl(Out);
571       Out << typeName << "->setBody(";
572     }
573
574     Out << typeName << "_fields, /*isPacked=*/"
575         << (ST->isPacked() ? "true" : "false") << ");";
576     nl(Out);
577     if (!ST->isLiteral()) {
578       Out << "}";
579       nl(Out);
580     }
581     break;
582   }
583   case Type::ArrayTyID: {
584     ArrayType* AT = cast<ArrayType>(Ty);
585     Type* ET = AT->getElementType();
586     printType(ET);
587     if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
588       std::string elemName(getCppName(ET));
589       Out << "ArrayType* " << typeName << " = ArrayType::get("
590           << elemName
591           << ", " << utostr(AT->getNumElements()) << ");";
592       nl(Out);
593     }
594     break;
595   }
596   case Type::PointerTyID: {
597     PointerType* PT = cast<PointerType>(Ty);
598     Type* ET = PT->getElementType();
599     printType(ET);
600     if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
601       std::string elemName(getCppName(ET));
602       Out << "PointerType* " << typeName << " = PointerType::get("
603           << elemName
604           << ", " << utostr(PT->getAddressSpace()) << ");";
605       nl(Out);
606     }
607     break;
608   }
609   case Type::VectorTyID: {
610     VectorType* PT = cast<VectorType>(Ty);
611     Type* ET = PT->getElementType();
612     printType(ET);
613     if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
614       std::string elemName(getCppName(ET));
615       Out << "VectorType* " << typeName << " = VectorType::get("
616           << elemName
617           << ", " << utostr(PT->getNumElements()) << ");";
618       nl(Out);
619     }
620     break;
621   }
622   default:
623     error("Invalid TypeID");
624   }
625
626   // Indicate that this type is now defined.
627   DefinedTypes.insert(Ty);
628
629   // Finally, separate the type definition from other with a newline.
630   nl(Out);
631 }
632
633 void CppWriter::printTypes(const Module* M) {
634   // Add all of the global variables to the value table.
635   for (Module::const_global_iterator I = TheModule->global_begin(),
636          E = TheModule->global_end(); I != E; ++I) {
637     if (I->hasInitializer())
638       printType(I->getInitializer()->getType());
639     printType(I->getType());
640   }
641
642   // Add all the functions to the table
643   for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
644        FI != FE; ++FI) {
645     printType(FI->getReturnType());
646     printType(FI->getFunctionType());
647     // Add all the function arguments
648     for (Function::const_arg_iterator AI = FI->arg_begin(),
649            AE = FI->arg_end(); AI != AE; ++AI) {
650       printType(AI->getType());
651     }
652
653     // Add all of the basic blocks and instructions
654     for (Function::const_iterator BB = FI->begin(),
655            E = FI->end(); BB != E; ++BB) {
656       printType(BB->getType());
657       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
658            ++I) {
659         printType(I->getType());
660         for (unsigned i = 0; i < I->getNumOperands(); ++i)
661           printType(I->getOperand(i)->getType());
662       }
663     }
664   }
665 }
666
667
668 // printConstant - Print out a constant pool entry...
669 void CppWriter::printConstant(const Constant *CV) {
670   // First, if the constant is actually a GlobalValue (variable or function)
671   // or its already in the constant list then we've printed it already and we
672   // can just return.
673   if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
674     return;
675
676   std::string constName(getCppName(CV));
677   std::string typeName(getCppName(CV->getType()));
678
679   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
680     std::string constValue = CI->getValue().toString(10, true);
681     Out << "ConstantInt* " << constName
682         << " = ConstantInt::get(mod->getContext(), APInt("
683         << cast<IntegerType>(CI->getType())->getBitWidth()
684         << ", StringRef(\"" <<  constValue << "\"), 10));";
685   } else if (isa<ConstantAggregateZero>(CV)) {
686     Out << "ConstantAggregateZero* " << constName
687         << " = ConstantAggregateZero::get(" << typeName << ");";
688   } else if (isa<ConstantPointerNull>(CV)) {
689     Out << "ConstantPointerNull* " << constName
690         << " = ConstantPointerNull::get(" << typeName << ");";
691   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
692     Out << "ConstantFP* " << constName << " = ";
693     printCFP(CFP);
694     Out << ";";
695   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
696     Out << "std::vector<Constant*> " << constName << "_elems;";
697     nl(Out);
698     unsigned N = CA->getNumOperands();
699     for (unsigned i = 0; i < N; ++i) {
700       printConstant(CA->getOperand(i)); // recurse to print operands
701       Out << constName << "_elems.push_back("
702           << getCppName(CA->getOperand(i)) << ");";
703       nl(Out);
704     }
705     Out << "Constant* " << constName << " = ConstantArray::get("
706         << typeName << ", " << constName << "_elems);";
707   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
708     Out << "std::vector<Constant*> " << constName << "_fields;";
709     nl(Out);
710     unsigned N = CS->getNumOperands();
711     for (unsigned i = 0; i < N; i++) {
712       printConstant(CS->getOperand(i));
713       Out << constName << "_fields.push_back("
714           << getCppName(CS->getOperand(i)) << ");";
715       nl(Out);
716     }
717     Out << "Constant* " << constName << " = ConstantStruct::get("
718         << typeName << ", " << constName << "_fields);";
719   } else if (const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
720     Out << "std::vector<Constant*> " << constName << "_elems;";
721     nl(Out);
722     unsigned N = CVec->getNumOperands();
723     for (unsigned i = 0; i < N; ++i) {
724       printConstant(CVec->getOperand(i));
725       Out << constName << "_elems.push_back("
726           << getCppName(CVec->getOperand(i)) << ");";
727       nl(Out);
728     }
729     Out << "Constant* " << constName << " = ConstantVector::get("
730         << typeName << ", " << constName << "_elems);";
731   } else if (isa<UndefValue>(CV)) {
732     Out << "UndefValue* " << constName << " = UndefValue::get("
733         << typeName << ");";
734   } else if (const ConstantDataSequential *CDS =
735                dyn_cast<ConstantDataSequential>(CV)) {
736     if (CDS->isString()) {
737       Out << "Constant *" << constName <<
738       " = ConstantDataArray::getString(mod->getContext(), \"";
739       StringRef Str = CDS->getAsString();
740       bool nullTerminate = false;
741       if (Str.back() == 0) {
742         Str = Str.drop_back();
743         nullTerminate = true;
744       }
745       printEscapedString(Str);
746       // Determine if we want null termination or not.
747       if (nullTerminate)
748         Out << "\", true);";
749       else
750         Out << "\", false);";// No null terminator
751     } else {
752       // TODO: Could generate more efficient code generating CDS calls instead.
753       Out << "std::vector<Constant*> " << constName << "_elems;";
754       nl(Out);
755       for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
756         Constant *Elt = CDS->getElementAsConstant(i);
757         printConstant(Elt);
758         Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
759         nl(Out);
760       }
761       Out << "Constant* " << constName;
762       
763       if (isa<ArrayType>(CDS->getType()))
764         Out << " = ConstantArray::get(";
765       else
766         Out << " = ConstantVector::get(";
767       Out << typeName << ", " << constName << "_elems);";
768     }
769   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
770     if (CE->getOpcode() == Instruction::GetElementPtr) {
771       Out << "std::vector<Constant*> " << constName << "_indices;";
772       nl(Out);
773       printConstant(CE->getOperand(0));
774       for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
775         printConstant(CE->getOperand(i));
776         Out << constName << "_indices.push_back("
777             << getCppName(CE->getOperand(i)) << ");";
778         nl(Out);
779       }
780       Out << "Constant* " << constName
781           << " = ConstantExpr::getGetElementPtr("
782           << getCppName(CE->getOperand(0)) << ", "
783           << constName << "_indices);";
784     } else if (CE->isCast()) {
785       printConstant(CE->getOperand(0));
786       Out << "Constant* " << constName << " = ConstantExpr::getCast(";
787       switch (CE->getOpcode()) {
788       default: llvm_unreachable("Invalid cast opcode");
789       case Instruction::Trunc: Out << "Instruction::Trunc"; break;
790       case Instruction::ZExt:  Out << "Instruction::ZExt"; break;
791       case Instruction::SExt:  Out << "Instruction::SExt"; break;
792       case Instruction::FPTrunc:  Out << "Instruction::FPTrunc"; break;
793       case Instruction::FPExt:  Out << "Instruction::FPExt"; break;
794       case Instruction::FPToUI:  Out << "Instruction::FPToUI"; break;
795       case Instruction::FPToSI:  Out << "Instruction::FPToSI"; break;
796       case Instruction::UIToFP:  Out << "Instruction::UIToFP"; break;
797       case Instruction::SIToFP:  Out << "Instruction::SIToFP"; break;
798       case Instruction::PtrToInt:  Out << "Instruction::PtrToInt"; break;
799       case Instruction::IntToPtr:  Out << "Instruction::IntToPtr"; break;
800       case Instruction::BitCast:  Out << "Instruction::BitCast"; break;
801       }
802       Out << ", " << getCppName(CE->getOperand(0)) << ", "
803           << getCppName(CE->getType()) << ");";
804     } else {
805       unsigned N = CE->getNumOperands();
806       for (unsigned i = 0; i < N; ++i ) {
807         printConstant(CE->getOperand(i));
808       }
809       Out << "Constant* " << constName << " = ConstantExpr::";
810       switch (CE->getOpcode()) {
811       case Instruction::Add:    Out << "getAdd(";  break;
812       case Instruction::FAdd:   Out << "getFAdd(";  break;
813       case Instruction::Sub:    Out << "getSub("; break;
814       case Instruction::FSub:   Out << "getFSub("; break;
815       case Instruction::Mul:    Out << "getMul("; break;
816       case Instruction::FMul:   Out << "getFMul("; break;
817       case Instruction::UDiv:   Out << "getUDiv("; break;
818       case Instruction::SDiv:   Out << "getSDiv("; break;
819       case Instruction::FDiv:   Out << "getFDiv("; break;
820       case Instruction::URem:   Out << "getURem("; break;
821       case Instruction::SRem:   Out << "getSRem("; break;
822       case Instruction::FRem:   Out << "getFRem("; break;
823       case Instruction::And:    Out << "getAnd("; break;
824       case Instruction::Or:     Out << "getOr("; break;
825       case Instruction::Xor:    Out << "getXor("; break;
826       case Instruction::ICmp:
827         Out << "getICmp(ICmpInst::ICMP_";
828         switch (CE->getPredicate()) {
829         case ICmpInst::ICMP_EQ:  Out << "EQ"; break;
830         case ICmpInst::ICMP_NE:  Out << "NE"; break;
831         case ICmpInst::ICMP_SLT: Out << "SLT"; break;
832         case ICmpInst::ICMP_ULT: Out << "ULT"; break;
833         case ICmpInst::ICMP_SGT: Out << "SGT"; break;
834         case ICmpInst::ICMP_UGT: Out << "UGT"; break;
835         case ICmpInst::ICMP_SLE: Out << "SLE"; break;
836         case ICmpInst::ICMP_ULE: Out << "ULE"; break;
837         case ICmpInst::ICMP_SGE: Out << "SGE"; break;
838         case ICmpInst::ICMP_UGE: Out << "UGE"; break;
839         default: error("Invalid ICmp Predicate");
840         }
841         break;
842       case Instruction::FCmp:
843         Out << "getFCmp(FCmpInst::FCMP_";
844         switch (CE->getPredicate()) {
845         case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
846         case FCmpInst::FCMP_ORD:   Out << "ORD"; break;
847         case FCmpInst::FCMP_UNO:   Out << "UNO"; break;
848         case FCmpInst::FCMP_OEQ:   Out << "OEQ"; break;
849         case FCmpInst::FCMP_UEQ:   Out << "UEQ"; break;
850         case FCmpInst::FCMP_ONE:   Out << "ONE"; break;
851         case FCmpInst::FCMP_UNE:   Out << "UNE"; break;
852         case FCmpInst::FCMP_OLT:   Out << "OLT"; break;
853         case FCmpInst::FCMP_ULT:   Out << "ULT"; break;
854         case FCmpInst::FCMP_OGT:   Out << "OGT"; break;
855         case FCmpInst::FCMP_UGT:   Out << "UGT"; break;
856         case FCmpInst::FCMP_OLE:   Out << "OLE"; break;
857         case FCmpInst::FCMP_ULE:   Out << "ULE"; break;
858         case FCmpInst::FCMP_OGE:   Out << "OGE"; break;
859         case FCmpInst::FCMP_UGE:   Out << "UGE"; break;
860         case FCmpInst::FCMP_TRUE:  Out << "TRUE"; break;
861         default: error("Invalid FCmp Predicate");
862         }
863         break;
864       case Instruction::Shl:     Out << "getShl("; break;
865       case Instruction::LShr:    Out << "getLShr("; break;
866       case Instruction::AShr:    Out << "getAShr("; break;
867       case Instruction::Select:  Out << "getSelect("; break;
868       case Instruction::ExtractElement: Out << "getExtractElement("; break;
869       case Instruction::InsertElement:  Out << "getInsertElement("; break;
870       case Instruction::ShuffleVector:  Out << "getShuffleVector("; break;
871       default:
872         error("Invalid constant expression");
873         break;
874       }
875       Out << getCppName(CE->getOperand(0));
876       for (unsigned i = 1; i < CE->getNumOperands(); ++i)
877         Out << ", " << getCppName(CE->getOperand(i));
878       Out << ");";
879     }
880   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
881     Out << "Constant* " << constName << " = ";
882     Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
883   } else {
884     error("Bad Constant");
885     Out << "Constant* " << constName << " = 0; ";
886   }
887   nl(Out);
888 }
889
890 void CppWriter::printConstants(const Module* M) {
891   // Traverse all the global variables looking for constant initializers
892   for (Module::const_global_iterator I = TheModule->global_begin(),
893          E = TheModule->global_end(); I != E; ++I)
894     if (I->hasInitializer())
895       printConstant(I->getInitializer());
896
897   // Traverse the LLVM functions looking for constants
898   for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
899        FI != FE; ++FI) {
900     // Add all of the basic blocks and instructions
901     for (Function::const_iterator BB = FI->begin(),
902            E = FI->end(); BB != E; ++BB) {
903       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
904            ++I) {
905         for (unsigned i = 0; i < I->getNumOperands(); ++i) {
906           if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
907             printConstant(C);
908           }
909         }
910       }
911     }
912   }
913 }
914
915 void CppWriter::printVariableUses(const GlobalVariable *GV) {
916   nl(Out) << "// Type Definitions";
917   nl(Out);
918   printType(GV->getType());
919   if (GV->hasInitializer()) {
920     const Constant *Init = GV->getInitializer();
921     printType(Init->getType());
922     if (const Function *F = dyn_cast<Function>(Init)) {
923       nl(Out)<< "/ Function Declarations"; nl(Out);
924       printFunctionHead(F);
925     } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
926       nl(Out) << "// Global Variable Declarations"; nl(Out);
927       printVariableHead(gv);
928       
929       nl(Out) << "// Global Variable Definitions"; nl(Out);
930       printVariableBody(gv);
931     } else  {
932       nl(Out) << "// Constant Definitions"; nl(Out);
933       printConstant(Init);
934     }
935   }
936 }
937
938 void CppWriter::printVariableHead(const GlobalVariable *GV) {
939   nl(Out) << "GlobalVariable* " << getCppName(GV);
940   if (is_inline) {
941     Out << " = mod->getGlobalVariable(mod->getContext(), ";
942     printEscapedString(GV->getName());
943     Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
944     nl(Out) << "if (!" << getCppName(GV) << ") {";
945     in(); nl(Out) << getCppName(GV);
946   }
947   Out << " = new GlobalVariable(/*Module=*/*mod, ";
948   nl(Out) << "/*Type=*/";
949   printCppName(GV->getType()->getElementType());
950   Out << ",";
951   nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
952   Out << ",";
953   nl(Out) << "/*Linkage=*/";
954   printLinkageType(GV->getLinkage());
955   Out << ",";
956   nl(Out) << "/*Initializer=*/0, ";
957   if (GV->hasInitializer()) {
958     Out << "// has initializer, specified below";
959   }
960   nl(Out) << "/*Name=*/\"";
961   printEscapedString(GV->getName());
962   Out << "\");";
963   nl(Out);
964
965   if (GV->hasSection()) {
966     printCppName(GV);
967     Out << "->setSection(\"";
968     printEscapedString(GV->getSection());
969     Out << "\");";
970     nl(Out);
971   }
972   if (GV->getAlignment()) {
973     printCppName(GV);
974     Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
975     nl(Out);
976   }
977   if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
978     printCppName(GV);
979     Out << "->setVisibility(";
980     printVisibilityType(GV->getVisibility());
981     Out << ");";
982     nl(Out);
983   }
984   if (GV->isThreadLocal()) {
985     printCppName(GV);
986     Out << "->setThreadLocal(true);";
987     nl(Out);
988   }
989   if (is_inline) {
990     out(); Out << "}"; nl(Out);
991   }
992 }
993
994 void CppWriter::printVariableBody(const GlobalVariable *GV) {
995   if (GV->hasInitializer()) {
996     printCppName(GV);
997     Out << "->setInitializer(";
998     Out << getCppName(GV->getInitializer()) << ");";
999     nl(Out);
1000   }
1001 }
1002
1003 std::string CppWriter::getOpName(const Value* V) {
1004   if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1005     return getCppName(V);
1006
1007   // See if its alread in the map of forward references, if so just return the
1008   // name we already set up for it
1009   ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1010   if (I != ForwardRefs.end())
1011     return I->second;
1012
1013   // This is a new forward reference. Generate a unique name for it
1014   std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1015
1016   // Yes, this is a hack. An Argument is the smallest instantiable value that
1017   // we can make as a placeholder for the real value. We'll replace these
1018   // Argument instances later.
1019   Out << "Argument* " << result << " = new Argument("
1020       << getCppName(V->getType()) << ");";
1021   nl(Out);
1022   ForwardRefs[V] = result;
1023   return result;
1024 }
1025
1026 static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
1027   switch (Ordering) {
1028     case NotAtomic: return "NotAtomic";
1029     case Unordered: return "Unordered";
1030     case Monotonic: return "Monotonic";
1031     case Acquire: return "Acquire";
1032     case Release: return "Release";
1033     case AcquireRelease: return "AcquireRelease";
1034     case SequentiallyConsistent: return "SequentiallyConsistent";
1035   }
1036   llvm_unreachable("Unknown ordering");
1037 }
1038
1039 static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
1040   switch (SynchScope) {
1041     case SingleThread: return "SingleThread";
1042     case CrossThread: return "CrossThread";
1043   }
1044   llvm_unreachable("Unknown synch scope");
1045 }
1046
1047 // printInstruction - This member is called for each Instruction in a function.
1048 void CppWriter::printInstruction(const Instruction *I,
1049                                  const std::string& bbname) {
1050   std::string iName(getCppName(I));
1051
1052   // Before we emit this instruction, we need to take care of generating any
1053   // forward references. So, we get the names of all the operands in advance
1054   const unsigned Ops(I->getNumOperands());
1055   std::string* opNames = new std::string[Ops];
1056   for (unsigned i = 0; i < Ops; i++)
1057     opNames[i] = getOpName(I->getOperand(i));
1058
1059   switch (I->getOpcode()) {
1060   default:
1061     error("Invalid instruction");
1062     break;
1063
1064   case Instruction::Ret: {
1065     const ReturnInst* ret =  cast<ReturnInst>(I);
1066     Out << "ReturnInst::Create(mod->getContext(), "
1067         << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1068     break;
1069   }
1070   case Instruction::Br: {
1071     const BranchInst* br = cast<BranchInst>(I);
1072     Out << "BranchInst::Create(" ;
1073     if (br->getNumOperands() == 3) {
1074       Out << opNames[2] << ", "
1075           << opNames[1] << ", "
1076           << opNames[0] << ", ";
1077
1078     } else if (br->getNumOperands() == 1) {
1079       Out << opNames[0] << ", ";
1080     } else {
1081       error("Branch with 2 operands?");
1082     }
1083     Out << bbname << ");";
1084     break;
1085   }
1086   case Instruction::Switch: {
1087     const SwitchInst *SI = cast<SwitchInst>(I);
1088     Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1089         << getOpName(SI->getCondition()) << ", "
1090         << getOpName(SI->getDefaultDest()) << ", "
1091         << SI->getNumCases() << ", " << bbname << ");";
1092     nl(Out);
1093     unsigned NumCases = SI->getNumCases();
1094     for (unsigned i = 0; i < NumCases; ++i) {
1095       const ConstantInt* CaseVal = SI->getCaseValue(i);
1096       const BasicBlock *BB = SI->getCaseSuccessor(i);
1097       Out << iName << "->addCase("
1098           << getOpName(CaseVal) << ", "
1099           << getOpName(BB) << ");";
1100       nl(Out);
1101     }
1102     break;
1103   }
1104   case Instruction::IndirectBr: {
1105     const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1106     Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1107         << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1108     nl(Out);
1109     for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1110       Out << iName << "->addDestination(" << opNames[i] << ");";
1111       nl(Out);
1112     }
1113     break;
1114   }
1115   case Instruction::Resume: {
1116     Out << "ResumeInst::Create(mod->getContext(), " << opNames[0]
1117         << ", " << bbname << ");";
1118     break;
1119   }
1120   case Instruction::Invoke: {
1121     const InvokeInst* inv = cast<InvokeInst>(I);
1122     Out << "std::vector<Value*> " << iName << "_params;";
1123     nl(Out);
1124     for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1125       Out << iName << "_params.push_back("
1126           << getOpName(inv->getArgOperand(i)) << ");";
1127       nl(Out);
1128     }
1129     // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1130     Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1131         << getOpName(inv->getCalledFunction()) << ", "
1132         << getOpName(inv->getNormalDest()) << ", "
1133         << getOpName(inv->getUnwindDest()) << ", "
1134         << iName << "_params, \"";
1135     printEscapedString(inv->getName());
1136     Out << "\", " << bbname << ");";
1137     nl(Out) << iName << "->setCallingConv(";
1138     printCallingConv(inv->getCallingConv());
1139     Out << ");";
1140     printAttributes(inv->getAttributes(), iName);
1141     Out << iName << "->setAttributes(" << iName << "_PAL);";
1142     nl(Out);
1143     break;
1144   }
1145   case Instruction::Unwind: {
1146     Out << "new UnwindInst("
1147         << bbname << ");";
1148     break;
1149   }
1150   case Instruction::Unreachable: {
1151     Out << "new UnreachableInst("
1152         << "mod->getContext(), "
1153         << bbname << ");";
1154     break;
1155   }
1156   case Instruction::Add:
1157   case Instruction::FAdd:
1158   case Instruction::Sub:
1159   case Instruction::FSub:
1160   case Instruction::Mul:
1161   case Instruction::FMul:
1162   case Instruction::UDiv:
1163   case Instruction::SDiv:
1164   case Instruction::FDiv:
1165   case Instruction::URem:
1166   case Instruction::SRem:
1167   case Instruction::FRem:
1168   case Instruction::And:
1169   case Instruction::Or:
1170   case Instruction::Xor:
1171   case Instruction::Shl:
1172   case Instruction::LShr:
1173   case Instruction::AShr:{
1174     Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1175     switch (I->getOpcode()) {
1176     case Instruction::Add: Out << "Instruction::Add"; break;
1177     case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1178     case Instruction::Sub: Out << "Instruction::Sub"; break;
1179     case Instruction::FSub: Out << "Instruction::FSub"; break;
1180     case Instruction::Mul: Out << "Instruction::Mul"; break;
1181     case Instruction::FMul: Out << "Instruction::FMul"; break;
1182     case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1183     case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1184     case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1185     case Instruction::URem:Out << "Instruction::URem"; break;
1186     case Instruction::SRem:Out << "Instruction::SRem"; break;
1187     case Instruction::FRem:Out << "Instruction::FRem"; break;
1188     case Instruction::And: Out << "Instruction::And"; break;
1189     case Instruction::Or:  Out << "Instruction::Or";  break;
1190     case Instruction::Xor: Out << "Instruction::Xor"; break;
1191     case Instruction::Shl: Out << "Instruction::Shl"; break;
1192     case Instruction::LShr:Out << "Instruction::LShr"; break;
1193     case Instruction::AShr:Out << "Instruction::AShr"; break;
1194     default: Out << "Instruction::BadOpCode"; break;
1195     }
1196     Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1197     printEscapedString(I->getName());
1198     Out << "\", " << bbname << ");";
1199     break;
1200   }
1201   case Instruction::FCmp: {
1202     Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1203     switch (cast<FCmpInst>(I)->getPredicate()) {
1204     case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1205     case FCmpInst::FCMP_OEQ  : Out << "FCmpInst::FCMP_OEQ"; break;
1206     case FCmpInst::FCMP_OGT  : Out << "FCmpInst::FCMP_OGT"; break;
1207     case FCmpInst::FCMP_OGE  : Out << "FCmpInst::FCMP_OGE"; break;
1208     case FCmpInst::FCMP_OLT  : Out << "FCmpInst::FCMP_OLT"; break;
1209     case FCmpInst::FCMP_OLE  : Out << "FCmpInst::FCMP_OLE"; break;
1210     case FCmpInst::FCMP_ONE  : Out << "FCmpInst::FCMP_ONE"; break;
1211     case FCmpInst::FCMP_ORD  : Out << "FCmpInst::FCMP_ORD"; break;
1212     case FCmpInst::FCMP_UNO  : Out << "FCmpInst::FCMP_UNO"; break;
1213     case FCmpInst::FCMP_UEQ  : Out << "FCmpInst::FCMP_UEQ"; break;
1214     case FCmpInst::FCMP_UGT  : Out << "FCmpInst::FCMP_UGT"; break;
1215     case FCmpInst::FCMP_UGE  : Out << "FCmpInst::FCMP_UGE"; break;
1216     case FCmpInst::FCMP_ULT  : Out << "FCmpInst::FCMP_ULT"; break;
1217     case FCmpInst::FCMP_ULE  : Out << "FCmpInst::FCMP_ULE"; break;
1218     case FCmpInst::FCMP_UNE  : Out << "FCmpInst::FCMP_UNE"; break;
1219     case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1220     default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1221     }
1222     Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1223     printEscapedString(I->getName());
1224     Out << "\");";
1225     break;
1226   }
1227   case Instruction::ICmp: {
1228     Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1229     switch (cast<ICmpInst>(I)->getPredicate()) {
1230     case ICmpInst::ICMP_EQ:  Out << "ICmpInst::ICMP_EQ";  break;
1231     case ICmpInst::ICMP_NE:  Out << "ICmpInst::ICMP_NE";  break;
1232     case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1233     case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1234     case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1235     case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1236     case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1237     case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1238     case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1239     case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1240     default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1241     }
1242     Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1243     printEscapedString(I->getName());
1244     Out << "\");";
1245     break;
1246   }
1247   case Instruction::Alloca: {
1248     const AllocaInst* allocaI = cast<AllocaInst>(I);
1249     Out << "AllocaInst* " << iName << " = new AllocaInst("
1250         << getCppName(allocaI->getAllocatedType()) << ", ";
1251     if (allocaI->isArrayAllocation())
1252       Out << opNames[0] << ", ";
1253     Out << "\"";
1254     printEscapedString(allocaI->getName());
1255     Out << "\", " << bbname << ");";
1256     if (allocaI->getAlignment())
1257       nl(Out) << iName << "->setAlignment("
1258           << allocaI->getAlignment() << ");";
1259     break;
1260   }
1261   case Instruction::Load: {
1262     const LoadInst* load = cast<LoadInst>(I);
1263     Out << "LoadInst* " << iName << " = new LoadInst("
1264         << opNames[0] << ", \"";
1265     printEscapedString(load->getName());
1266     Out << "\", " << (load->isVolatile() ? "true" : "false" )
1267         << ", " << bbname << ");";
1268     if (load->getAlignment())
1269       nl(Out) << iName << "->setAlignment("
1270               << load->getAlignment() << ");";
1271     if (load->isAtomic()) {
1272       StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1273       StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1274       nl(Out) << iName << "->setAtomic("
1275               << Ordering << ", " << CrossThread << ");";
1276     }
1277     break;
1278   }
1279   case Instruction::Store: {
1280     const StoreInst* store = cast<StoreInst>(I);
1281     Out << "StoreInst* " << iName << " = new StoreInst("
1282         << opNames[0] << ", "
1283         << opNames[1] << ", "
1284         << (store->isVolatile() ? "true" : "false")
1285         << ", " << bbname << ");";
1286     if (store->getAlignment())
1287       nl(Out) << iName << "->setAlignment("
1288               << store->getAlignment() << ");";
1289     if (store->isAtomic()) {
1290       StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1291       StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1292       nl(Out) << iName << "->setAtomic("
1293               << Ordering << ", " << CrossThread << ");";
1294     }
1295     break;
1296   }
1297   case Instruction::GetElementPtr: {
1298     const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1299     if (gep->getNumOperands() <= 2) {
1300       Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1301           << opNames[0];
1302       if (gep->getNumOperands() == 2)
1303         Out << ", " << opNames[1];
1304     } else {
1305       Out << "std::vector<Value*> " << iName << "_indices;";
1306       nl(Out);
1307       for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1308         Out << iName << "_indices.push_back("
1309             << opNames[i] << ");";
1310         nl(Out);
1311       }
1312       Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1313           << opNames[0] << ", " << iName << "_indices";
1314     }
1315     Out << ", \"";
1316     printEscapedString(gep->getName());
1317     Out << "\", " << bbname << ");";
1318     break;
1319   }
1320   case Instruction::PHI: {
1321     const PHINode* phi = cast<PHINode>(I);
1322
1323     Out << "PHINode* " << iName << " = PHINode::Create("
1324         << getCppName(phi->getType()) << ", "
1325         << phi->getNumIncomingValues() << ", \"";
1326     printEscapedString(phi->getName());
1327     Out << "\", " << bbname << ");";
1328     nl(Out);
1329     for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
1330       Out << iName << "->addIncoming("
1331           << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
1332           << getOpName(phi->getIncomingBlock(i)) << ");";
1333       nl(Out);
1334     }
1335     break;
1336   }
1337   case Instruction::Trunc:
1338   case Instruction::ZExt:
1339   case Instruction::SExt:
1340   case Instruction::FPTrunc:
1341   case Instruction::FPExt:
1342   case Instruction::FPToUI:
1343   case Instruction::FPToSI:
1344   case Instruction::UIToFP:
1345   case Instruction::SIToFP:
1346   case Instruction::PtrToInt:
1347   case Instruction::IntToPtr:
1348   case Instruction::BitCast: {
1349     const CastInst* cst = cast<CastInst>(I);
1350     Out << "CastInst* " << iName << " = new ";
1351     switch (I->getOpcode()) {
1352     case Instruction::Trunc:    Out << "TruncInst"; break;
1353     case Instruction::ZExt:     Out << "ZExtInst"; break;
1354     case Instruction::SExt:     Out << "SExtInst"; break;
1355     case Instruction::FPTrunc:  Out << "FPTruncInst"; break;
1356     case Instruction::FPExt:    Out << "FPExtInst"; break;
1357     case Instruction::FPToUI:   Out << "FPToUIInst"; break;
1358     case Instruction::FPToSI:   Out << "FPToSIInst"; break;
1359     case Instruction::UIToFP:   Out << "UIToFPInst"; break;
1360     case Instruction::SIToFP:   Out << "SIToFPInst"; break;
1361     case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1362     case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1363     case Instruction::BitCast:  Out << "BitCastInst"; break;
1364     default: assert(0 && "Unreachable"); break;
1365     }
1366     Out << "(" << opNames[0] << ", "
1367         << getCppName(cst->getType()) << ", \"";
1368     printEscapedString(cst->getName());
1369     Out << "\", " << bbname << ");";
1370     break;
1371   }
1372   case Instruction::Call: {
1373     const CallInst* call = cast<CallInst>(I);
1374     if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1375       Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1376           << getCppName(ila->getFunctionType()) << ", \""
1377           << ila->getAsmString() << "\", \""
1378           << ila->getConstraintString() << "\","
1379           << (ila->hasSideEffects() ? "true" : "false") << ");";
1380       nl(Out);
1381     }
1382     if (call->getNumArgOperands() > 1) {
1383       Out << "std::vector<Value*> " << iName << "_params;";
1384       nl(Out);
1385       for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
1386         Out << iName << "_params.push_back(" << opNames[i] << ");";
1387         nl(Out);
1388       }
1389       Out << "CallInst* " << iName << " = CallInst::Create("
1390           << opNames[call->getNumArgOperands()] << ", "
1391           << iName << "_params, \"";
1392     } else if (call->getNumArgOperands() == 1) {
1393       Out << "CallInst* " << iName << " = CallInst::Create("
1394           << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
1395     } else {
1396       Out << "CallInst* " << iName << " = CallInst::Create("
1397           << opNames[call->getNumArgOperands()] << ", \"";
1398     }
1399     printEscapedString(call->getName());
1400     Out << "\", " << bbname << ");";
1401     nl(Out) << iName << "->setCallingConv(";
1402     printCallingConv(call->getCallingConv());
1403     Out << ");";
1404     nl(Out) << iName << "->setTailCall("
1405         << (call->isTailCall() ? "true" : "false");
1406     Out << ");";
1407     nl(Out);
1408     printAttributes(call->getAttributes(), iName);
1409     Out << iName << "->setAttributes(" << iName << "_PAL);";
1410     nl(Out);
1411     break;
1412   }
1413   case Instruction::Select: {
1414     const SelectInst* sel = cast<SelectInst>(I);
1415     Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1416     Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1417     printEscapedString(sel->getName());
1418     Out << "\", " << bbname << ");";
1419     break;
1420   }
1421   case Instruction::UserOp1:
1422     /// FALL THROUGH
1423   case Instruction::UserOp2: {
1424     /// FIXME: What should be done here?
1425     break;
1426   }
1427   case Instruction::VAArg: {
1428     const VAArgInst* va = cast<VAArgInst>(I);
1429     Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1430         << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1431     printEscapedString(va->getName());
1432     Out << "\", " << bbname << ");";
1433     break;
1434   }
1435   case Instruction::ExtractElement: {
1436     const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1437     Out << "ExtractElementInst* " << getCppName(eei)
1438         << " = new ExtractElementInst(" << opNames[0]
1439         << ", " << opNames[1] << ", \"";
1440     printEscapedString(eei->getName());
1441     Out << "\", " << bbname << ");";
1442     break;
1443   }
1444   case Instruction::InsertElement: {
1445     const InsertElementInst* iei = cast<InsertElementInst>(I);
1446     Out << "InsertElementInst* " << getCppName(iei)
1447         << " = InsertElementInst::Create(" << opNames[0]
1448         << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1449     printEscapedString(iei->getName());
1450     Out << "\", " << bbname << ");";
1451     break;
1452   }
1453   case Instruction::ShuffleVector: {
1454     const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1455     Out << "ShuffleVectorInst* " << getCppName(svi)
1456         << " = new ShuffleVectorInst(" << opNames[0]
1457         << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1458     printEscapedString(svi->getName());
1459     Out << "\", " << bbname << ");";
1460     break;
1461   }
1462   case Instruction::ExtractValue: {
1463     const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1464     Out << "std::vector<unsigned> " << iName << "_indices;";
1465     nl(Out);
1466     for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1467       Out << iName << "_indices.push_back("
1468           << evi->idx_begin()[i] << ");";
1469       nl(Out);
1470     }
1471     Out << "ExtractValueInst* " << getCppName(evi)
1472         << " = ExtractValueInst::Create(" << opNames[0]
1473         << ", "
1474         << iName << "_indices, \"";
1475     printEscapedString(evi->getName());
1476     Out << "\", " << bbname << ");";
1477     break;
1478   }
1479   case Instruction::InsertValue: {
1480     const InsertValueInst *ivi = cast<InsertValueInst>(I);
1481     Out << "std::vector<unsigned> " << iName << "_indices;";
1482     nl(Out);
1483     for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1484       Out << iName << "_indices.push_back("
1485           << ivi->idx_begin()[i] << ");";
1486       nl(Out);
1487     }
1488     Out << "InsertValueInst* " << getCppName(ivi)
1489         << " = InsertValueInst::Create(" << opNames[0]
1490         << ", " << opNames[1] << ", "
1491         << iName << "_indices, \"";
1492     printEscapedString(ivi->getName());
1493     Out << "\", " << bbname << ");";
1494     break;
1495   }
1496   case Instruction::Fence: {
1497     const FenceInst *fi = cast<FenceInst>(I);
1498     StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1499     StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1500     Out << "FenceInst* " << iName
1501         << " = new FenceInst(mod->getContext(), "
1502         << Ordering << ", " << CrossThread << ", " << bbname
1503         << ");";
1504     break;
1505   }
1506   case Instruction::AtomicCmpXchg: {
1507     const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1508     StringRef Ordering = ConvertAtomicOrdering(cxi->getOrdering());
1509     StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1510     Out << "AtomicCmpXchgInst* " << iName
1511         << " = new AtomicCmpXchgInst("
1512         << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
1513         << Ordering << ", " << CrossThread << ", " << bbname
1514         << ");";
1515     nl(Out) << iName << "->setName(\"";
1516     printEscapedString(cxi->getName());
1517     Out << "\");";
1518     break;
1519   }
1520   case Instruction::AtomicRMW: {
1521     const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1522     StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1523     StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1524     StringRef Operation;
1525     switch (rmwi->getOperation()) {
1526       case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1527       case AtomicRMWInst::Add:  Operation = "AtomicRMWInst::Add"; break;
1528       case AtomicRMWInst::Sub:  Operation = "AtomicRMWInst::Sub"; break;
1529       case AtomicRMWInst::And:  Operation = "AtomicRMWInst::And"; break;
1530       case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1531       case AtomicRMWInst::Or:   Operation = "AtomicRMWInst::Or"; break;
1532       case AtomicRMWInst::Xor:  Operation = "AtomicRMWInst::Xor"; break;
1533       case AtomicRMWInst::Max:  Operation = "AtomicRMWInst::Max"; break;
1534       case AtomicRMWInst::Min:  Operation = "AtomicRMWInst::Min"; break;
1535       case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1536       case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1537       case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1538     }
1539     Out << "AtomicRMWInst* " << iName
1540         << " = new AtomicRMWInst("
1541         << Operation << ", "
1542         << opNames[0] << ", " << opNames[1] << ", "
1543         << Ordering << ", " << CrossThread << ", " << bbname
1544         << ");";
1545     nl(Out) << iName << "->setName(\"";
1546     printEscapedString(rmwi->getName());
1547     Out << "\");";
1548     break;
1549   }
1550   }
1551   DefinedValues.insert(I);
1552   nl(Out);
1553   delete [] opNames;
1554 }
1555
1556 // Print out the types, constants and declarations needed by one function
1557 void CppWriter::printFunctionUses(const Function* F) {
1558   nl(Out) << "// Type Definitions"; nl(Out);
1559   if (!is_inline) {
1560     // Print the function's return type
1561     printType(F->getReturnType());
1562
1563     // Print the function's function type
1564     printType(F->getFunctionType());
1565
1566     // Print the types of each of the function's arguments
1567     for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1568          AI != AE; ++AI) {
1569       printType(AI->getType());
1570     }
1571   }
1572
1573   // Print type definitions for every type referenced by an instruction and
1574   // make a note of any global values or constants that are referenced
1575   SmallPtrSet<GlobalValue*,64> gvs;
1576   SmallPtrSet<Constant*,64> consts;
1577   for (Function::const_iterator BB = F->begin(), BE = F->end();
1578        BB != BE; ++BB){
1579     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1580          I != E; ++I) {
1581       // Print the type of the instruction itself
1582       printType(I->getType());
1583
1584       // Print the type of each of the instruction's operands
1585       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1586         Value* operand = I->getOperand(i);
1587         printType(operand->getType());
1588
1589         // If the operand references a GVal or Constant, make a note of it
1590         if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1591           gvs.insert(GV);
1592           if (GenerationType != GenFunction)
1593             if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1594               if (GVar->hasInitializer())
1595                 consts.insert(GVar->getInitializer());
1596         } else if (Constant* C = dyn_cast<Constant>(operand)) {
1597           consts.insert(C);
1598           for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1599             // If the operand references a GVal or Constant, make a note of it
1600             Value* operand = C->getOperand(j);
1601             printType(operand->getType());
1602             if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1603               gvs.insert(GV);
1604               if (GenerationType != GenFunction)
1605                 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1606                   if (GVar->hasInitializer())
1607                     consts.insert(GVar->getInitializer());
1608             }
1609           }
1610         }
1611       }
1612     }
1613   }
1614
1615   // Print the function declarations for any functions encountered
1616   nl(Out) << "// Function Declarations"; nl(Out);
1617   for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1618        I != E; ++I) {
1619     if (Function* Fun = dyn_cast<Function>(*I)) {
1620       if (!is_inline || Fun != F)
1621         printFunctionHead(Fun);
1622     }
1623   }
1624
1625   // Print the global variable declarations for any variables encountered
1626   nl(Out) << "// Global Variable Declarations"; nl(Out);
1627   for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1628        I != E; ++I) {
1629     if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1630       printVariableHead(F);
1631   }
1632
1633   // Print the constants found
1634   nl(Out) << "// Constant Definitions"; nl(Out);
1635   for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1636          E = consts.end(); I != E; ++I) {
1637     printConstant(*I);
1638   }
1639
1640   // Process the global variables definitions now that all the constants have
1641   // been emitted. These definitions just couple the gvars with their constant
1642   // initializers.
1643   if (GenerationType != GenFunction) {
1644     nl(Out) << "// Global Variable Definitions"; nl(Out);
1645     for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1646          I != E; ++I) {
1647       if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1648         printVariableBody(GV);
1649     }
1650   }
1651 }
1652
1653 void CppWriter::printFunctionHead(const Function* F) {
1654   nl(Out) << "Function* " << getCppName(F);
1655   Out << " = mod->getFunction(\"";
1656   printEscapedString(F->getName());
1657   Out << "\");";
1658   nl(Out) << "if (!" << getCppName(F) << ") {";
1659   nl(Out) << getCppName(F);
1660
1661   Out<< " = Function::Create(";
1662   nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1663   nl(Out) << "/*Linkage=*/";
1664   printLinkageType(F->getLinkage());
1665   Out << ",";
1666   nl(Out) << "/*Name=*/\"";
1667   printEscapedString(F->getName());
1668   Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1669   nl(Out,-1);
1670   printCppName(F);
1671   Out << "->setCallingConv(";
1672   printCallingConv(F->getCallingConv());
1673   Out << ");";
1674   nl(Out);
1675   if (F->hasSection()) {
1676     printCppName(F);
1677     Out << "->setSection(\"" << F->getSection() << "\");";
1678     nl(Out);
1679   }
1680   if (F->getAlignment()) {
1681     printCppName(F);
1682     Out << "->setAlignment(" << F->getAlignment() << ");";
1683     nl(Out);
1684   }
1685   if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1686     printCppName(F);
1687     Out << "->setVisibility(";
1688     printVisibilityType(F->getVisibility());
1689     Out << ");";
1690     nl(Out);
1691   }
1692   if (F->hasGC()) {
1693     printCppName(F);
1694     Out << "->setGC(\"" << F->getGC() << "\");";
1695     nl(Out);
1696   }
1697   Out << "}";
1698   nl(Out);
1699   printAttributes(F->getAttributes(), getCppName(F));
1700   printCppName(F);
1701   Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1702   nl(Out);
1703 }
1704
1705 void CppWriter::printFunctionBody(const Function *F) {
1706   if (F->isDeclaration())
1707     return; // external functions have no bodies.
1708
1709   // Clear the DefinedValues and ForwardRefs maps because we can't have
1710   // cross-function forward refs
1711   ForwardRefs.clear();
1712   DefinedValues.clear();
1713
1714   // Create all the argument values
1715   if (!is_inline) {
1716     if (!F->arg_empty()) {
1717       Out << "Function::arg_iterator args = " << getCppName(F)
1718           << "->arg_begin();";
1719       nl(Out);
1720     }
1721     for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1722          AI != AE; ++AI) {
1723       Out << "Value* " << getCppName(AI) << " = args++;";
1724       nl(Out);
1725       if (AI->hasName()) {
1726         Out << getCppName(AI) << "->setName(\"";
1727         printEscapedString(AI->getName());
1728         Out << "\");";
1729         nl(Out);
1730       }
1731     }
1732   }
1733
1734   // Create all the basic blocks
1735   nl(Out);
1736   for (Function::const_iterator BI = F->begin(), BE = F->end();
1737        BI != BE; ++BI) {
1738     std::string bbname(getCppName(BI));
1739     Out << "BasicBlock* " << bbname <<
1740            " = BasicBlock::Create(mod->getContext(), \"";
1741     if (BI->hasName())
1742       printEscapedString(BI->getName());
1743     Out << "\"," << getCppName(BI->getParent()) << ",0);";
1744     nl(Out);
1745   }
1746
1747   // Output all of its basic blocks... for the function
1748   for (Function::const_iterator BI = F->begin(), BE = F->end();
1749        BI != BE; ++BI) {
1750     std::string bbname(getCppName(BI));
1751     nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1752     nl(Out);
1753
1754     // Output all of the instructions in the basic block...
1755     for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1756          I != E; ++I) {
1757       printInstruction(I,bbname);
1758     }
1759   }
1760
1761   // Loop over the ForwardRefs and resolve them now that all instructions
1762   // are generated.
1763   if (!ForwardRefs.empty()) {
1764     nl(Out) << "// Resolve Forward References";
1765     nl(Out);
1766   }
1767
1768   while (!ForwardRefs.empty()) {
1769     ForwardRefMap::iterator I = ForwardRefs.begin();
1770     Out << I->second << "->replaceAllUsesWith("
1771         << getCppName(I->first) << "); delete " << I->second << ";";
1772     nl(Out);
1773     ForwardRefs.erase(I);
1774   }
1775 }
1776
1777 void CppWriter::printInline(const std::string& fname,
1778                             const std::string& func) {
1779   const Function* F = TheModule->getFunction(func);
1780   if (!F) {
1781     error(std::string("Function '") + func + "' not found in input module");
1782     return;
1783   }
1784   if (F->isDeclaration()) {
1785     error(std::string("Function '") + func + "' is external!");
1786     return;
1787   }
1788   nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1789           << getCppName(F);
1790   unsigned arg_count = 1;
1791   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1792        AI != AE; ++AI) {
1793     Out << ", Value* arg_" << arg_count;
1794   }
1795   Out << ") {";
1796   nl(Out);
1797   is_inline = true;
1798   printFunctionUses(F);
1799   printFunctionBody(F);
1800   is_inline = false;
1801   Out << "return " << getCppName(F->begin()) << ";";
1802   nl(Out) << "}";
1803   nl(Out);
1804 }
1805
1806 void CppWriter::printModuleBody() {
1807   // Print out all the type definitions
1808   nl(Out) << "// Type Definitions"; nl(Out);
1809   printTypes(TheModule);
1810
1811   // Functions can call each other and global variables can reference them so
1812   // define all the functions first before emitting their function bodies.
1813   nl(Out) << "// Function Declarations"; nl(Out);
1814   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1815        I != E; ++I)
1816     printFunctionHead(I);
1817
1818   // Process the global variables declarations. We can't initialze them until
1819   // after the constants are printed so just print a header for each global
1820   nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1821   for (Module::const_global_iterator I = TheModule->global_begin(),
1822          E = TheModule->global_end(); I != E; ++I) {
1823     printVariableHead(I);
1824   }
1825
1826   // Print out all the constants definitions. Constants don't recurse except
1827   // through GlobalValues. All GlobalValues have been declared at this point
1828   // so we can proceed to generate the constants.
1829   nl(Out) << "// Constant Definitions"; nl(Out);
1830   printConstants(TheModule);
1831
1832   // Process the global variables definitions now that all the constants have
1833   // been emitted. These definitions just couple the gvars with their constant
1834   // initializers.
1835   nl(Out) << "// Global Variable Definitions"; nl(Out);
1836   for (Module::const_global_iterator I = TheModule->global_begin(),
1837          E = TheModule->global_end(); I != E; ++I) {
1838     printVariableBody(I);
1839   }
1840
1841   // Finally, we can safely put out all of the function bodies.
1842   nl(Out) << "// Function Definitions"; nl(Out);
1843   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1844        I != E; ++I) {
1845     if (!I->isDeclaration()) {
1846       nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1847               << ")";
1848       nl(Out) << "{";
1849       nl(Out,1);
1850       printFunctionBody(I);
1851       nl(Out,-1) << "}";
1852       nl(Out);
1853     }
1854   }
1855 }
1856
1857 void CppWriter::printProgram(const std::string& fname,
1858                              const std::string& mName) {
1859   Out << "#include <llvm/LLVMContext.h>\n";
1860   Out << "#include <llvm/Module.h>\n";
1861   Out << "#include <llvm/DerivedTypes.h>\n";
1862   Out << "#include <llvm/Constants.h>\n";
1863   Out << "#include <llvm/GlobalVariable.h>\n";
1864   Out << "#include <llvm/Function.h>\n";
1865   Out << "#include <llvm/CallingConv.h>\n";
1866   Out << "#include <llvm/BasicBlock.h>\n";
1867   Out << "#include <llvm/Instructions.h>\n";
1868   Out << "#include <llvm/InlineAsm.h>\n";
1869   Out << "#include <llvm/Support/FormattedStream.h>\n";
1870   Out << "#include <llvm/Support/MathExtras.h>\n";
1871   Out << "#include <llvm/Pass.h>\n";
1872   Out << "#include <llvm/PassManager.h>\n";
1873   Out << "#include <llvm/ADT/SmallVector.h>\n";
1874   Out << "#include <llvm/Analysis/Verifier.h>\n";
1875   Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1876   Out << "#include <algorithm>\n";
1877   Out << "using namespace llvm;\n\n";
1878   Out << "Module* " << fname << "();\n\n";
1879   Out << "int main(int argc, char**argv) {\n";
1880   Out << "  Module* Mod = " << fname << "();\n";
1881   Out << "  verifyModule(*Mod, PrintMessageAction);\n";
1882   Out << "  PassManager PM;\n";
1883   Out << "  PM.add(createPrintModulePass(&outs()));\n";
1884   Out << "  PM.run(*Mod);\n";
1885   Out << "  return 0;\n";
1886   Out << "}\n\n";
1887   printModule(fname,mName);
1888 }
1889
1890 void CppWriter::printModule(const std::string& fname,
1891                             const std::string& mName) {
1892   nl(Out) << "Module* " << fname << "() {";
1893   nl(Out,1) << "// Module Construction";
1894   nl(Out) << "Module* mod = new Module(\"";
1895   printEscapedString(mName);
1896   Out << "\", getGlobalContext());";
1897   if (!TheModule->getTargetTriple().empty()) {
1898     nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1899   }
1900   if (!TheModule->getTargetTriple().empty()) {
1901     nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1902             << "\");";
1903   }
1904
1905   if (!TheModule->getModuleInlineAsm().empty()) {
1906     nl(Out) << "mod->setModuleInlineAsm(\"";
1907     printEscapedString(TheModule->getModuleInlineAsm());
1908     Out << "\");";
1909   }
1910   nl(Out);
1911
1912   // Loop over the dependent libraries and emit them.
1913   Module::lib_iterator LI = TheModule->lib_begin();
1914   Module::lib_iterator LE = TheModule->lib_end();
1915   while (LI != LE) {
1916     Out << "mod->addLibrary(\"" << *LI << "\");";
1917     nl(Out);
1918     ++LI;
1919   }
1920   printModuleBody();
1921   nl(Out) << "return mod;";
1922   nl(Out,-1) << "}";
1923   nl(Out);
1924 }
1925
1926 void CppWriter::printContents(const std::string& fname,
1927                               const std::string& mName) {
1928   Out << "\nModule* " << fname << "(Module *mod) {\n";
1929   Out << "\nmod->setModuleIdentifier(\"";
1930   printEscapedString(mName);
1931   Out << "\");\n";
1932   printModuleBody();
1933   Out << "\nreturn mod;\n";
1934   Out << "\n}\n";
1935 }
1936
1937 void CppWriter::printFunction(const std::string& fname,
1938                               const std::string& funcName) {
1939   const Function* F = TheModule->getFunction(funcName);
1940   if (!F) {
1941     error(std::string("Function '") + funcName + "' not found in input module");
1942     return;
1943   }
1944   Out << "\nFunction* " << fname << "(Module *mod) {\n";
1945   printFunctionUses(F);
1946   printFunctionHead(F);
1947   printFunctionBody(F);
1948   Out << "return " << getCppName(F) << ";\n";
1949   Out << "}\n";
1950 }
1951
1952 void CppWriter::printFunctions() {
1953   const Module::FunctionListType &funcs = TheModule->getFunctionList();
1954   Module::const_iterator I  = funcs.begin();
1955   Module::const_iterator IE = funcs.end();
1956
1957   for (; I != IE; ++I) {
1958     const Function &func = *I;
1959     if (!func.isDeclaration()) {
1960       std::string name("define_");
1961       name += func.getName();
1962       printFunction(name, func.getName());
1963     }
1964   }
1965 }
1966
1967 void CppWriter::printVariable(const std::string& fname,
1968                               const std::string& varName) {
1969   const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1970
1971   if (!GV) {
1972     error(std::string("Variable '") + varName + "' not found in input module");
1973     return;
1974   }
1975   Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1976   printVariableUses(GV);
1977   printVariableHead(GV);
1978   printVariableBody(GV);
1979   Out << "return " << getCppName(GV) << ";\n";
1980   Out << "}\n";
1981 }
1982
1983 void CppWriter::printType(const std::string &fname,
1984                           const std::string &typeName) {
1985   Type* Ty = TheModule->getTypeByName(typeName);
1986   if (!Ty) {
1987     error(std::string("Type '") + typeName + "' not found in input module");
1988     return;
1989   }
1990   Out << "\nType* " << fname << "(Module *mod) {\n";
1991   printType(Ty);
1992   Out << "return " << getCppName(Ty) << ";\n";
1993   Out << "}\n";
1994 }
1995
1996 bool CppWriter::runOnModule(Module &M) {
1997   TheModule = &M;
1998
1999   // Emit a header
2000   Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
2001
2002   // Get the name of the function we're supposed to generate
2003   std::string fname = FuncName.getValue();
2004
2005   // Get the name of the thing we are to generate
2006   std::string tgtname = NameToGenerate.getValue();
2007   if (GenerationType == GenModule ||
2008       GenerationType == GenContents ||
2009       GenerationType == GenProgram ||
2010       GenerationType == GenFunctions) {
2011     if (tgtname == "!bad!") {
2012       if (M.getModuleIdentifier() == "-")
2013         tgtname = "<stdin>";
2014       else
2015         tgtname = M.getModuleIdentifier();
2016     }
2017   } else if (tgtname == "!bad!")
2018     error("You must use the -for option with -gen-{function,variable,type}");
2019
2020   switch (WhatToGenerate(GenerationType)) {
2021    case GenProgram:
2022     if (fname.empty())
2023       fname = "makeLLVMModule";
2024     printProgram(fname,tgtname);
2025     break;
2026    case GenModule:
2027     if (fname.empty())
2028       fname = "makeLLVMModule";
2029     printModule(fname,tgtname);
2030     break;
2031    case GenContents:
2032     if (fname.empty())
2033       fname = "makeLLVMModuleContents";
2034     printContents(fname,tgtname);
2035     break;
2036    case GenFunction:
2037     if (fname.empty())
2038       fname = "makeLLVMFunction";
2039     printFunction(fname,tgtname);
2040     break;
2041    case GenFunctions:
2042     printFunctions();
2043     break;
2044    case GenInline:
2045     if (fname.empty())
2046       fname = "makeLLVMInline";
2047     printInline(fname,tgtname);
2048     break;
2049    case GenVariable:
2050     if (fname.empty())
2051       fname = "makeLLVMVariable";
2052     printVariable(fname,tgtname);
2053     break;
2054    case GenType:
2055     if (fname.empty())
2056       fname = "makeLLVMType";
2057     printType(fname,tgtname);
2058     break;
2059   }
2060
2061   return false;
2062 }
2063
2064 char CppWriter::ID = 0;
2065
2066 //===----------------------------------------------------------------------===//
2067 //                       External Interface declaration
2068 //===----------------------------------------------------------------------===//
2069
2070 bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2071                                            formatted_raw_ostream &o,
2072                                            CodeGenFileType FileType,
2073                                            bool DisableVerify) {
2074   if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
2075   PM.add(new CppWriter(o));
2076   return false;
2077 }