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