Use Attributes::None instead of 0 after r148553 change on Attributes from unsigned...
[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 (isa<GlobalValue>(CV)) {
680     // Skip variables and functions, we emit them elsewhere
681     return;
682   }
683
684   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
685     std::string constValue = CI->getValue().toString(10, true);
686     Out << "ConstantInt* " << constName
687         << " = ConstantInt::get(mod->getContext(), APInt("
688         << cast<IntegerType>(CI->getType())->getBitWidth()
689         << ", StringRef(\"" <<  constValue << "\"), 10));";
690   } else if (isa<ConstantAggregateZero>(CV)) {
691     Out << "ConstantAggregateZero* " << constName
692         << " = ConstantAggregateZero::get(" << typeName << ");";
693   } else if (isa<ConstantPointerNull>(CV)) {
694     Out << "ConstantPointerNull* " << constName
695         << " = ConstantPointerNull::get(" << typeName << ");";
696   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
697     Out << "ConstantFP* " << constName << " = ";
698     printCFP(CFP);
699     Out << ";";
700   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
701     if (CA->isString() &&
702         CA->getType()->getElementType() ==
703             Type::getInt8Ty(CA->getContext())) {
704       Out << "Constant* " << constName <<
705              " = ConstantArray::get(mod->getContext(), \"";
706       std::string tmp = CA->getAsString();
707       bool nullTerminate = false;
708       if (tmp[tmp.length()-1] == 0) {
709         tmp.erase(tmp.length()-1);
710         nullTerminate = true;
711       }
712       printEscapedString(tmp);
713       // Determine if we want null termination or not.
714       if (nullTerminate)
715         Out << "\", true"; // Indicate that the null terminator should be
716                            // added.
717       else
718         Out << "\", false";// No null terminator
719       Out << ");";
720     } else {
721       Out << "std::vector<Constant*> " << constName << "_elems;";
722       nl(Out);
723       unsigned N = CA->getNumOperands();
724       for (unsigned i = 0; i < N; ++i) {
725         printConstant(CA->getOperand(i)); // recurse to print operands
726         Out << constName << "_elems.push_back("
727             << getCppName(CA->getOperand(i)) << ");";
728         nl(Out);
729       }
730       Out << "Constant* " << constName << " = ConstantArray::get("
731           << typeName << ", " << constName << "_elems);";
732     }
733   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
734     Out << "std::vector<Constant*> " << constName << "_fields;";
735     nl(Out);
736     unsigned N = CS->getNumOperands();
737     for (unsigned i = 0; i < N; i++) {
738       printConstant(CS->getOperand(i));
739       Out << constName << "_fields.push_back("
740           << getCppName(CS->getOperand(i)) << ");";
741       nl(Out);
742     }
743     Out << "Constant* " << constName << " = ConstantStruct::get("
744         << typeName << ", " << constName << "_fields);";
745   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
746     Out << "std::vector<Constant*> " << constName << "_elems;";
747     nl(Out);
748     unsigned N = CP->getNumOperands();
749     for (unsigned i = 0; i < N; ++i) {
750       printConstant(CP->getOperand(i));
751       Out << constName << "_elems.push_back("
752           << getCppName(CP->getOperand(i)) << ");";
753       nl(Out);
754     }
755     Out << "Constant* " << constName << " = ConstantVector::get("
756         << typeName << ", " << constName << "_elems);";
757   } else if (isa<UndefValue>(CV)) {
758     Out << "UndefValue* " << constName << " = UndefValue::get("
759         << typeName << ");";
760   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
761     if (CE->getOpcode() == Instruction::GetElementPtr) {
762       Out << "std::vector<Constant*> " << constName << "_indices;";
763       nl(Out);
764       printConstant(CE->getOperand(0));
765       for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
766         printConstant(CE->getOperand(i));
767         Out << constName << "_indices.push_back("
768             << getCppName(CE->getOperand(i)) << ");";
769         nl(Out);
770       }
771       Out << "Constant* " << constName
772           << " = ConstantExpr::getGetElementPtr("
773           << getCppName(CE->getOperand(0)) << ", "
774           << constName << "_indices);";
775     } else if (CE->isCast()) {
776       printConstant(CE->getOperand(0));
777       Out << "Constant* " << constName << " = ConstantExpr::getCast(";
778       switch (CE->getOpcode()) {
779       default: llvm_unreachable("Invalid cast opcode");
780       case Instruction::Trunc: Out << "Instruction::Trunc"; break;
781       case Instruction::ZExt:  Out << "Instruction::ZExt"; break;
782       case Instruction::SExt:  Out << "Instruction::SExt"; break;
783       case Instruction::FPTrunc:  Out << "Instruction::FPTrunc"; break;
784       case Instruction::FPExt:  Out << "Instruction::FPExt"; break;
785       case Instruction::FPToUI:  Out << "Instruction::FPToUI"; break;
786       case Instruction::FPToSI:  Out << "Instruction::FPToSI"; break;
787       case Instruction::UIToFP:  Out << "Instruction::UIToFP"; break;
788       case Instruction::SIToFP:  Out << "Instruction::SIToFP"; break;
789       case Instruction::PtrToInt:  Out << "Instruction::PtrToInt"; break;
790       case Instruction::IntToPtr:  Out << "Instruction::IntToPtr"; break;
791       case Instruction::BitCast:  Out << "Instruction::BitCast"; break;
792       }
793       Out << ", " << getCppName(CE->getOperand(0)) << ", "
794           << getCppName(CE->getType()) << ");";
795     } else {
796       unsigned N = CE->getNumOperands();
797       for (unsigned i = 0; i < N; ++i ) {
798         printConstant(CE->getOperand(i));
799       }
800       Out << "Constant* " << constName << " = ConstantExpr::";
801       switch (CE->getOpcode()) {
802       case Instruction::Add:    Out << "getAdd(";  break;
803       case Instruction::FAdd:   Out << "getFAdd(";  break;
804       case Instruction::Sub:    Out << "getSub("; break;
805       case Instruction::FSub:   Out << "getFSub("; break;
806       case Instruction::Mul:    Out << "getMul("; break;
807       case Instruction::FMul:   Out << "getFMul("; break;
808       case Instruction::UDiv:   Out << "getUDiv("; break;
809       case Instruction::SDiv:   Out << "getSDiv("; break;
810       case Instruction::FDiv:   Out << "getFDiv("; break;
811       case Instruction::URem:   Out << "getURem("; break;
812       case Instruction::SRem:   Out << "getSRem("; break;
813       case Instruction::FRem:   Out << "getFRem("; break;
814       case Instruction::And:    Out << "getAnd("; break;
815       case Instruction::Or:     Out << "getOr("; break;
816       case Instruction::Xor:    Out << "getXor("; break;
817       case Instruction::ICmp:
818         Out << "getICmp(ICmpInst::ICMP_";
819         switch (CE->getPredicate()) {
820         case ICmpInst::ICMP_EQ:  Out << "EQ"; break;
821         case ICmpInst::ICMP_NE:  Out << "NE"; break;
822         case ICmpInst::ICMP_SLT: Out << "SLT"; break;
823         case ICmpInst::ICMP_ULT: Out << "ULT"; break;
824         case ICmpInst::ICMP_SGT: Out << "SGT"; break;
825         case ICmpInst::ICMP_UGT: Out << "UGT"; break;
826         case ICmpInst::ICMP_SLE: Out << "SLE"; break;
827         case ICmpInst::ICMP_ULE: Out << "ULE"; break;
828         case ICmpInst::ICMP_SGE: Out << "SGE"; break;
829         case ICmpInst::ICMP_UGE: Out << "UGE"; break;
830         default: error("Invalid ICmp Predicate");
831         }
832         break;
833       case Instruction::FCmp:
834         Out << "getFCmp(FCmpInst::FCMP_";
835         switch (CE->getPredicate()) {
836         case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
837         case FCmpInst::FCMP_ORD:   Out << "ORD"; break;
838         case FCmpInst::FCMP_UNO:   Out << "UNO"; break;
839         case FCmpInst::FCMP_OEQ:   Out << "OEQ"; break;
840         case FCmpInst::FCMP_UEQ:   Out << "UEQ"; break;
841         case FCmpInst::FCMP_ONE:   Out << "ONE"; break;
842         case FCmpInst::FCMP_UNE:   Out << "UNE"; break;
843         case FCmpInst::FCMP_OLT:   Out << "OLT"; break;
844         case FCmpInst::FCMP_ULT:   Out << "ULT"; break;
845         case FCmpInst::FCMP_OGT:   Out << "OGT"; break;
846         case FCmpInst::FCMP_UGT:   Out << "UGT"; break;
847         case FCmpInst::FCMP_OLE:   Out << "OLE"; break;
848         case FCmpInst::FCMP_ULE:   Out << "ULE"; break;
849         case FCmpInst::FCMP_OGE:   Out << "OGE"; break;
850         case FCmpInst::FCMP_UGE:   Out << "UGE"; break;
851         case FCmpInst::FCMP_TRUE:  Out << "TRUE"; break;
852         default: error("Invalid FCmp Predicate");
853         }
854         break;
855       case Instruction::Shl:     Out << "getShl("; break;
856       case Instruction::LShr:    Out << "getLShr("; break;
857       case Instruction::AShr:    Out << "getAShr("; break;
858       case Instruction::Select:  Out << "getSelect("; break;
859       case Instruction::ExtractElement: Out << "getExtractElement("; break;
860       case Instruction::InsertElement:  Out << "getInsertElement("; break;
861       case Instruction::ShuffleVector:  Out << "getShuffleVector("; break;
862       default:
863         error("Invalid constant expression");
864         break;
865       }
866       Out << getCppName(CE->getOperand(0));
867       for (unsigned i = 1; i < CE->getNumOperands(); ++i)
868         Out << ", " << getCppName(CE->getOperand(i));
869       Out << ");";
870     }
871   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
872     Out << "Constant* " << constName << " = ";
873     Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
874   } else {
875     error("Bad Constant");
876     Out << "Constant* " << constName << " = 0; ";
877   }
878   nl(Out);
879 }
880
881 void CppWriter::printConstants(const Module* M) {
882   // Traverse all the global variables looking for constant initializers
883   for (Module::const_global_iterator I = TheModule->global_begin(),
884          E = TheModule->global_end(); I != E; ++I)
885     if (I->hasInitializer())
886       printConstant(I->getInitializer());
887
888   // Traverse the LLVM functions looking for constants
889   for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
890        FI != FE; ++FI) {
891     // Add all of the basic blocks and instructions
892     for (Function::const_iterator BB = FI->begin(),
893            E = FI->end(); BB != E; ++BB) {
894       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
895            ++I) {
896         for (unsigned i = 0; i < I->getNumOperands(); ++i) {
897           if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
898             printConstant(C);
899           }
900         }
901       }
902     }
903   }
904 }
905
906 void CppWriter::printVariableUses(const GlobalVariable *GV) {
907   nl(Out) << "// Type Definitions";
908   nl(Out);
909   printType(GV->getType());
910   if (GV->hasInitializer()) {
911     const Constant *Init = GV->getInitializer();
912     printType(Init->getType());
913     if (const Function *F = dyn_cast<Function>(Init)) {
914       nl(Out)<< "/ Function Declarations"; nl(Out);
915       printFunctionHead(F);
916     } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
917       nl(Out) << "// Global Variable Declarations"; nl(Out);
918       printVariableHead(gv);
919       
920       nl(Out) << "// Global Variable Definitions"; nl(Out);
921       printVariableBody(gv);
922     } else  {
923       nl(Out) << "// Constant Definitions"; nl(Out);
924       printConstant(Init);
925     }
926   }
927 }
928
929 void CppWriter::printVariableHead(const GlobalVariable *GV) {
930   nl(Out) << "GlobalVariable* " << getCppName(GV);
931   if (is_inline) {
932     Out << " = mod->getGlobalVariable(mod->getContext(), ";
933     printEscapedString(GV->getName());
934     Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
935     nl(Out) << "if (!" << getCppName(GV) << ") {";
936     in(); nl(Out) << getCppName(GV);
937   }
938   Out << " = new GlobalVariable(/*Module=*/*mod, ";
939   nl(Out) << "/*Type=*/";
940   printCppName(GV->getType()->getElementType());
941   Out << ",";
942   nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
943   Out << ",";
944   nl(Out) << "/*Linkage=*/";
945   printLinkageType(GV->getLinkage());
946   Out << ",";
947   nl(Out) << "/*Initializer=*/0, ";
948   if (GV->hasInitializer()) {
949     Out << "// has initializer, specified below";
950   }
951   nl(Out) << "/*Name=*/\"";
952   printEscapedString(GV->getName());
953   Out << "\");";
954   nl(Out);
955
956   if (GV->hasSection()) {
957     printCppName(GV);
958     Out << "->setSection(\"";
959     printEscapedString(GV->getSection());
960     Out << "\");";
961     nl(Out);
962   }
963   if (GV->getAlignment()) {
964     printCppName(GV);
965     Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
966     nl(Out);
967   }
968   if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
969     printCppName(GV);
970     Out << "->setVisibility(";
971     printVisibilityType(GV->getVisibility());
972     Out << ");";
973     nl(Out);
974   }
975   if (GV->isThreadLocal()) {
976     printCppName(GV);
977     Out << "->setThreadLocal(true);";
978     nl(Out);
979   }
980   if (is_inline) {
981     out(); Out << "}"; nl(Out);
982   }
983 }
984
985 void CppWriter::printVariableBody(const GlobalVariable *GV) {
986   if (GV->hasInitializer()) {
987     printCppName(GV);
988     Out << "->setInitializer(";
989     Out << getCppName(GV->getInitializer()) << ");";
990     nl(Out);
991   }
992 }
993
994 std::string CppWriter::getOpName(const Value* V) {
995   if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
996     return getCppName(V);
997
998   // See if its alread in the map of forward references, if so just return the
999   // name we already set up for it
1000   ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1001   if (I != ForwardRefs.end())
1002     return I->second;
1003
1004   // This is a new forward reference. Generate a unique name for it
1005   std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1006
1007   // Yes, this is a hack. An Argument is the smallest instantiable value that
1008   // we can make as a placeholder for the real value. We'll replace these
1009   // Argument instances later.
1010   Out << "Argument* " << result << " = new Argument("
1011       << getCppName(V->getType()) << ");";
1012   nl(Out);
1013   ForwardRefs[V] = result;
1014   return result;
1015 }
1016
1017 static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
1018   switch (Ordering) {
1019     case NotAtomic: return "NotAtomic";
1020     case Unordered: return "Unordered";
1021     case Monotonic: return "Monotonic";
1022     case Acquire: return "Acquire";
1023     case Release: return "Release";
1024     case AcquireRelease: return "AcquireRelease";
1025     case SequentiallyConsistent: return "SequentiallyConsistent";
1026   }
1027   llvm_unreachable("Unknown ordering");
1028 }
1029
1030 static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
1031   switch (SynchScope) {
1032     case SingleThread: return "SingleThread";
1033     case CrossThread: return "CrossThread";
1034   }
1035   llvm_unreachable("Unknown synch scope");
1036 }
1037
1038 // printInstruction - This member is called for each Instruction in a function.
1039 void CppWriter::printInstruction(const Instruction *I,
1040                                  const std::string& bbname) {
1041   std::string iName(getCppName(I));
1042
1043   // Before we emit this instruction, we need to take care of generating any
1044   // forward references. So, we get the names of all the operands in advance
1045   const unsigned Ops(I->getNumOperands());
1046   std::string* opNames = new std::string[Ops];
1047   for (unsigned i = 0; i < Ops; i++)
1048     opNames[i] = getOpName(I->getOperand(i));
1049
1050   switch (I->getOpcode()) {
1051   default:
1052     error("Invalid instruction");
1053     break;
1054
1055   case Instruction::Ret: {
1056     const ReturnInst* ret =  cast<ReturnInst>(I);
1057     Out << "ReturnInst::Create(mod->getContext(), "
1058         << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1059     break;
1060   }
1061   case Instruction::Br: {
1062     const BranchInst* br = cast<BranchInst>(I);
1063     Out << "BranchInst::Create(" ;
1064     if (br->getNumOperands() == 3) {
1065       Out << opNames[2] << ", "
1066           << opNames[1] << ", "
1067           << opNames[0] << ", ";
1068
1069     } else if (br->getNumOperands() == 1) {
1070       Out << opNames[0] << ", ";
1071     } else {
1072       error("Branch with 2 operands?");
1073     }
1074     Out << bbname << ");";
1075     break;
1076   }
1077   case Instruction::Switch: {
1078     const SwitchInst *SI = cast<SwitchInst>(I);
1079     Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1080         << getOpName(SI->getCondition()) << ", "
1081         << getOpName(SI->getDefaultDest()) << ", "
1082         << SI->getNumCases() << ", " << bbname << ");";
1083     nl(Out);
1084     unsigned NumCases = SI->getNumCases();
1085     for (unsigned i = 1; i < NumCases; ++i) {
1086       const ConstantInt* CaseVal = SI->getCaseValue(i);
1087       const BasicBlock* BB = SI->getSuccessor(i);
1088       Out << iName << "->addCase("
1089           << getOpName(CaseVal) << ", "
1090           << getOpName(BB) << ");";
1091       nl(Out);
1092     }
1093     break;
1094   }
1095   case Instruction::IndirectBr: {
1096     const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1097     Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1098         << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1099     nl(Out);
1100     for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1101       Out << iName << "->addDestination(" << opNames[i] << ");";
1102       nl(Out);
1103     }
1104     break;
1105   }
1106   case Instruction::Resume: {
1107     Out << "ResumeInst::Create(mod->getContext(), " << opNames[0]
1108         << ", " << bbname << ");";
1109     break;
1110   }
1111   case Instruction::Invoke: {
1112     const InvokeInst* inv = cast<InvokeInst>(I);
1113     Out << "std::vector<Value*> " << iName << "_params;";
1114     nl(Out);
1115     for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1116       Out << iName << "_params.push_back("
1117           << getOpName(inv->getArgOperand(i)) << ");";
1118       nl(Out);
1119     }
1120     // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1121     Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1122         << getOpName(inv->getCalledFunction()) << ", "
1123         << getOpName(inv->getNormalDest()) << ", "
1124         << getOpName(inv->getUnwindDest()) << ", "
1125         << iName << "_params, \"";
1126     printEscapedString(inv->getName());
1127     Out << "\", " << bbname << ");";
1128     nl(Out) << iName << "->setCallingConv(";
1129     printCallingConv(inv->getCallingConv());
1130     Out << ");";
1131     printAttributes(inv->getAttributes(), iName);
1132     Out << iName << "->setAttributes(" << iName << "_PAL);";
1133     nl(Out);
1134     break;
1135   }
1136   case Instruction::Unwind: {
1137     Out << "new UnwindInst("
1138         << bbname << ");";
1139     break;
1140   }
1141   case Instruction::Unreachable: {
1142     Out << "new UnreachableInst("
1143         << "mod->getContext(), "
1144         << bbname << ");";
1145     break;
1146   }
1147   case Instruction::Add:
1148   case Instruction::FAdd:
1149   case Instruction::Sub:
1150   case Instruction::FSub:
1151   case Instruction::Mul:
1152   case Instruction::FMul:
1153   case Instruction::UDiv:
1154   case Instruction::SDiv:
1155   case Instruction::FDiv:
1156   case Instruction::URem:
1157   case Instruction::SRem:
1158   case Instruction::FRem:
1159   case Instruction::And:
1160   case Instruction::Or:
1161   case Instruction::Xor:
1162   case Instruction::Shl:
1163   case Instruction::LShr:
1164   case Instruction::AShr:{
1165     Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1166     switch (I->getOpcode()) {
1167     case Instruction::Add: Out << "Instruction::Add"; break;
1168     case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1169     case Instruction::Sub: Out << "Instruction::Sub"; break;
1170     case Instruction::FSub: Out << "Instruction::FSub"; break;
1171     case Instruction::Mul: Out << "Instruction::Mul"; break;
1172     case Instruction::FMul: Out << "Instruction::FMul"; break;
1173     case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1174     case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1175     case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1176     case Instruction::URem:Out << "Instruction::URem"; break;
1177     case Instruction::SRem:Out << "Instruction::SRem"; break;
1178     case Instruction::FRem:Out << "Instruction::FRem"; break;
1179     case Instruction::And: Out << "Instruction::And"; break;
1180     case Instruction::Or:  Out << "Instruction::Or";  break;
1181     case Instruction::Xor: Out << "Instruction::Xor"; break;
1182     case Instruction::Shl: Out << "Instruction::Shl"; break;
1183     case Instruction::LShr:Out << "Instruction::LShr"; break;
1184     case Instruction::AShr:Out << "Instruction::AShr"; break;
1185     default: Out << "Instruction::BadOpCode"; break;
1186     }
1187     Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1188     printEscapedString(I->getName());
1189     Out << "\", " << bbname << ");";
1190     break;
1191   }
1192   case Instruction::FCmp: {
1193     Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1194     switch (cast<FCmpInst>(I)->getPredicate()) {
1195     case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1196     case FCmpInst::FCMP_OEQ  : Out << "FCmpInst::FCMP_OEQ"; break;
1197     case FCmpInst::FCMP_OGT  : Out << "FCmpInst::FCMP_OGT"; break;
1198     case FCmpInst::FCMP_OGE  : Out << "FCmpInst::FCMP_OGE"; break;
1199     case FCmpInst::FCMP_OLT  : Out << "FCmpInst::FCMP_OLT"; break;
1200     case FCmpInst::FCMP_OLE  : Out << "FCmpInst::FCMP_OLE"; break;
1201     case FCmpInst::FCMP_ONE  : Out << "FCmpInst::FCMP_ONE"; break;
1202     case FCmpInst::FCMP_ORD  : Out << "FCmpInst::FCMP_ORD"; break;
1203     case FCmpInst::FCMP_UNO  : Out << "FCmpInst::FCMP_UNO"; break;
1204     case FCmpInst::FCMP_UEQ  : Out << "FCmpInst::FCMP_UEQ"; break;
1205     case FCmpInst::FCMP_UGT  : Out << "FCmpInst::FCMP_UGT"; break;
1206     case FCmpInst::FCMP_UGE  : Out << "FCmpInst::FCMP_UGE"; break;
1207     case FCmpInst::FCMP_ULT  : Out << "FCmpInst::FCMP_ULT"; break;
1208     case FCmpInst::FCMP_ULE  : Out << "FCmpInst::FCMP_ULE"; break;
1209     case FCmpInst::FCMP_UNE  : Out << "FCmpInst::FCMP_UNE"; break;
1210     case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1211     default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1212     }
1213     Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1214     printEscapedString(I->getName());
1215     Out << "\");";
1216     break;
1217   }
1218   case Instruction::ICmp: {
1219     Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1220     switch (cast<ICmpInst>(I)->getPredicate()) {
1221     case ICmpInst::ICMP_EQ:  Out << "ICmpInst::ICMP_EQ";  break;
1222     case ICmpInst::ICMP_NE:  Out << "ICmpInst::ICMP_NE";  break;
1223     case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1224     case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1225     case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1226     case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1227     case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1228     case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1229     case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1230     case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1231     default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1232     }
1233     Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1234     printEscapedString(I->getName());
1235     Out << "\");";
1236     break;
1237   }
1238   case Instruction::Alloca: {
1239     const AllocaInst* allocaI = cast<AllocaInst>(I);
1240     Out << "AllocaInst* " << iName << " = new AllocaInst("
1241         << getCppName(allocaI->getAllocatedType()) << ", ";
1242     if (allocaI->isArrayAllocation())
1243       Out << opNames[0] << ", ";
1244     Out << "\"";
1245     printEscapedString(allocaI->getName());
1246     Out << "\", " << bbname << ");";
1247     if (allocaI->getAlignment())
1248       nl(Out) << iName << "->setAlignment("
1249           << allocaI->getAlignment() << ");";
1250     break;
1251   }
1252   case Instruction::Load: {
1253     const LoadInst* load = cast<LoadInst>(I);
1254     Out << "LoadInst* " << iName << " = new LoadInst("
1255         << opNames[0] << ", \"";
1256     printEscapedString(load->getName());
1257     Out << "\", " << (load->isVolatile() ? "true" : "false" )
1258         << ", " << bbname << ");";
1259     if (load->getAlignment())
1260       nl(Out) << iName << "->setAlignment("
1261               << load->getAlignment() << ");";
1262     if (load->isAtomic()) {
1263       StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1264       StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1265       nl(Out) << iName << "->setAtomic("
1266               << Ordering << ", " << CrossThread << ");";
1267     }
1268     break;
1269   }
1270   case Instruction::Store: {
1271     const StoreInst* store = cast<StoreInst>(I);
1272     Out << "StoreInst* " << iName << " = new StoreInst("
1273         << opNames[0] << ", "
1274         << opNames[1] << ", "
1275         << (store->isVolatile() ? "true" : "false")
1276         << ", " << bbname << ");";
1277     if (store->getAlignment())
1278       nl(Out) << iName << "->setAlignment("
1279               << store->getAlignment() << ");";
1280     if (store->isAtomic()) {
1281       StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1282       StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1283       nl(Out) << iName << "->setAtomic("
1284               << Ordering << ", " << CrossThread << ");";
1285     }
1286     break;
1287   }
1288   case Instruction::GetElementPtr: {
1289     const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1290     if (gep->getNumOperands() <= 2) {
1291       Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1292           << opNames[0];
1293       if (gep->getNumOperands() == 2)
1294         Out << ", " << opNames[1];
1295     } else {
1296       Out << "std::vector<Value*> " << iName << "_indices;";
1297       nl(Out);
1298       for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1299         Out << iName << "_indices.push_back("
1300             << opNames[i] << ");";
1301         nl(Out);
1302       }
1303       Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1304           << opNames[0] << ", " << iName << "_indices";
1305     }
1306     Out << ", \"";
1307     printEscapedString(gep->getName());
1308     Out << "\", " << bbname << ");";
1309     break;
1310   }
1311   case Instruction::PHI: {
1312     const PHINode* phi = cast<PHINode>(I);
1313
1314     Out << "PHINode* " << iName << " = PHINode::Create("
1315         << getCppName(phi->getType()) << ", "
1316         << phi->getNumIncomingValues() << ", \"";
1317     printEscapedString(phi->getName());
1318     Out << "\", " << bbname << ");";
1319     nl(Out);
1320     for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
1321       Out << iName << "->addIncoming("
1322           << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
1323           << getOpName(phi->getIncomingBlock(i)) << ");";
1324       nl(Out);
1325     }
1326     break;
1327   }
1328   case Instruction::Trunc:
1329   case Instruction::ZExt:
1330   case Instruction::SExt:
1331   case Instruction::FPTrunc:
1332   case Instruction::FPExt:
1333   case Instruction::FPToUI:
1334   case Instruction::FPToSI:
1335   case Instruction::UIToFP:
1336   case Instruction::SIToFP:
1337   case Instruction::PtrToInt:
1338   case Instruction::IntToPtr:
1339   case Instruction::BitCast: {
1340     const CastInst* cst = cast<CastInst>(I);
1341     Out << "CastInst* " << iName << " = new ";
1342     switch (I->getOpcode()) {
1343     case Instruction::Trunc:    Out << "TruncInst"; break;
1344     case Instruction::ZExt:     Out << "ZExtInst"; break;
1345     case Instruction::SExt:     Out << "SExtInst"; break;
1346     case Instruction::FPTrunc:  Out << "FPTruncInst"; break;
1347     case Instruction::FPExt:    Out << "FPExtInst"; break;
1348     case Instruction::FPToUI:   Out << "FPToUIInst"; break;
1349     case Instruction::FPToSI:   Out << "FPToSIInst"; break;
1350     case Instruction::UIToFP:   Out << "UIToFPInst"; break;
1351     case Instruction::SIToFP:   Out << "SIToFPInst"; break;
1352     case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1353     case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1354     case Instruction::BitCast:  Out << "BitCastInst"; break;
1355     default: assert(0 && "Unreachable"); break;
1356     }
1357     Out << "(" << opNames[0] << ", "
1358         << getCppName(cst->getType()) << ", \"";
1359     printEscapedString(cst->getName());
1360     Out << "\", " << bbname << ");";
1361     break;
1362   }
1363   case Instruction::Call: {
1364     const CallInst* call = cast<CallInst>(I);
1365     if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1366       Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1367           << getCppName(ila->getFunctionType()) << ", \""
1368           << ila->getAsmString() << "\", \""
1369           << ila->getConstraintString() << "\","
1370           << (ila->hasSideEffects() ? "true" : "false") << ");";
1371       nl(Out);
1372     }
1373     if (call->getNumArgOperands() > 1) {
1374       Out << "std::vector<Value*> " << iName << "_params;";
1375       nl(Out);
1376       for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
1377         Out << iName << "_params.push_back(" << opNames[i] << ");";
1378         nl(Out);
1379       }
1380       Out << "CallInst* " << iName << " = CallInst::Create("
1381           << opNames[call->getNumArgOperands()] << ", "
1382           << iName << "_params, \"";
1383     } else if (call->getNumArgOperands() == 1) {
1384       Out << "CallInst* " << iName << " = CallInst::Create("
1385           << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
1386     } else {
1387       Out << "CallInst* " << iName << " = CallInst::Create("
1388           << opNames[call->getNumArgOperands()] << ", \"";
1389     }
1390     printEscapedString(call->getName());
1391     Out << "\", " << bbname << ");";
1392     nl(Out) << iName << "->setCallingConv(";
1393     printCallingConv(call->getCallingConv());
1394     Out << ");";
1395     nl(Out) << iName << "->setTailCall("
1396         << (call->isTailCall() ? "true" : "false");
1397     Out << ");";
1398     nl(Out);
1399     printAttributes(call->getAttributes(), iName);
1400     Out << iName << "->setAttributes(" << iName << "_PAL);";
1401     nl(Out);
1402     break;
1403   }
1404   case Instruction::Select: {
1405     const SelectInst* sel = cast<SelectInst>(I);
1406     Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1407     Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1408     printEscapedString(sel->getName());
1409     Out << "\", " << bbname << ");";
1410     break;
1411   }
1412   case Instruction::UserOp1:
1413     /// FALL THROUGH
1414   case Instruction::UserOp2: {
1415     /// FIXME: What should be done here?
1416     break;
1417   }
1418   case Instruction::VAArg: {
1419     const VAArgInst* va = cast<VAArgInst>(I);
1420     Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1421         << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1422     printEscapedString(va->getName());
1423     Out << "\", " << bbname << ");";
1424     break;
1425   }
1426   case Instruction::ExtractElement: {
1427     const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1428     Out << "ExtractElementInst* " << getCppName(eei)
1429         << " = new ExtractElementInst(" << opNames[0]
1430         << ", " << opNames[1] << ", \"";
1431     printEscapedString(eei->getName());
1432     Out << "\", " << bbname << ");";
1433     break;
1434   }
1435   case Instruction::InsertElement: {
1436     const InsertElementInst* iei = cast<InsertElementInst>(I);
1437     Out << "InsertElementInst* " << getCppName(iei)
1438         << " = InsertElementInst::Create(" << opNames[0]
1439         << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1440     printEscapedString(iei->getName());
1441     Out << "\", " << bbname << ");";
1442     break;
1443   }
1444   case Instruction::ShuffleVector: {
1445     const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1446     Out << "ShuffleVectorInst* " << getCppName(svi)
1447         << " = new ShuffleVectorInst(" << opNames[0]
1448         << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1449     printEscapedString(svi->getName());
1450     Out << "\", " << bbname << ");";
1451     break;
1452   }
1453   case Instruction::ExtractValue: {
1454     const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1455     Out << "std::vector<unsigned> " << iName << "_indices;";
1456     nl(Out);
1457     for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1458       Out << iName << "_indices.push_back("
1459           << evi->idx_begin()[i] << ");";
1460       nl(Out);
1461     }
1462     Out << "ExtractValueInst* " << getCppName(evi)
1463         << " = ExtractValueInst::Create(" << opNames[0]
1464         << ", "
1465         << iName << "_indices, \"";
1466     printEscapedString(evi->getName());
1467     Out << "\", " << bbname << ");";
1468     break;
1469   }
1470   case Instruction::InsertValue: {
1471     const InsertValueInst *ivi = cast<InsertValueInst>(I);
1472     Out << "std::vector<unsigned> " << iName << "_indices;";
1473     nl(Out);
1474     for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1475       Out << iName << "_indices.push_back("
1476           << ivi->idx_begin()[i] << ");";
1477       nl(Out);
1478     }
1479     Out << "InsertValueInst* " << getCppName(ivi)
1480         << " = InsertValueInst::Create(" << opNames[0]
1481         << ", " << opNames[1] << ", "
1482         << iName << "_indices, \"";
1483     printEscapedString(ivi->getName());
1484     Out << "\", " << bbname << ");";
1485     break;
1486   }
1487   case Instruction::Fence: {
1488     const FenceInst *fi = cast<FenceInst>(I);
1489     StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1490     StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1491     Out << "FenceInst* " << iName
1492         << " = new FenceInst(mod->getContext(), "
1493         << Ordering << ", " << CrossThread << ", " << bbname
1494         << ");";
1495     break;
1496   }
1497   case Instruction::AtomicCmpXchg: {
1498     const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1499     StringRef Ordering = ConvertAtomicOrdering(cxi->getOrdering());
1500     StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1501     Out << "AtomicCmpXchgInst* " << iName
1502         << " = new AtomicCmpXchgInst("
1503         << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
1504         << Ordering << ", " << CrossThread << ", " << bbname
1505         << ");";
1506     nl(Out) << iName << "->setName(\"";
1507     printEscapedString(cxi->getName());
1508     Out << "\");";
1509     break;
1510   }
1511   case Instruction::AtomicRMW: {
1512     const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1513     StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1514     StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1515     StringRef Operation;
1516     switch (rmwi->getOperation()) {
1517       case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1518       case AtomicRMWInst::Add:  Operation = "AtomicRMWInst::Add"; break;
1519       case AtomicRMWInst::Sub:  Operation = "AtomicRMWInst::Sub"; break;
1520       case AtomicRMWInst::And:  Operation = "AtomicRMWInst::And"; break;
1521       case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1522       case AtomicRMWInst::Or:   Operation = "AtomicRMWInst::Or"; break;
1523       case AtomicRMWInst::Xor:  Operation = "AtomicRMWInst::Xor"; break;
1524       case AtomicRMWInst::Max:  Operation = "AtomicRMWInst::Max"; break;
1525       case AtomicRMWInst::Min:  Operation = "AtomicRMWInst::Min"; break;
1526       case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1527       case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1528       case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1529     }
1530     Out << "AtomicRMWInst* " << iName
1531         << " = new AtomicRMWInst("
1532         << Operation << ", "
1533         << opNames[0] << ", " << opNames[1] << ", "
1534         << Ordering << ", " << CrossThread << ", " << bbname
1535         << ");";
1536     nl(Out) << iName << "->setName(\"";
1537     printEscapedString(rmwi->getName());
1538     Out << "\");";
1539     break;
1540   }
1541   }
1542   DefinedValues.insert(I);
1543   nl(Out);
1544   delete [] opNames;
1545 }
1546
1547 // Print out the types, constants and declarations needed by one function
1548 void CppWriter::printFunctionUses(const Function* F) {
1549   nl(Out) << "// Type Definitions"; nl(Out);
1550   if (!is_inline) {
1551     // Print the function's return type
1552     printType(F->getReturnType());
1553
1554     // Print the function's function type
1555     printType(F->getFunctionType());
1556
1557     // Print the types of each of the function's arguments
1558     for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1559          AI != AE; ++AI) {
1560       printType(AI->getType());
1561     }
1562   }
1563
1564   // Print type definitions for every type referenced by an instruction and
1565   // make a note of any global values or constants that are referenced
1566   SmallPtrSet<GlobalValue*,64> gvs;
1567   SmallPtrSet<Constant*,64> consts;
1568   for (Function::const_iterator BB = F->begin(), BE = F->end();
1569        BB != BE; ++BB){
1570     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1571          I != E; ++I) {
1572       // Print the type of the instruction itself
1573       printType(I->getType());
1574
1575       // Print the type of each of the instruction's operands
1576       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1577         Value* operand = I->getOperand(i);
1578         printType(operand->getType());
1579
1580         // If the operand references a GVal or Constant, make a note of it
1581         if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1582           gvs.insert(GV);
1583           if (GenerationType != GenFunction)
1584             if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1585               if (GVar->hasInitializer())
1586                 consts.insert(GVar->getInitializer());
1587         } else if (Constant* C = dyn_cast<Constant>(operand)) {
1588           consts.insert(C);
1589           for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1590             // If the operand references a GVal or Constant, make a note of it
1591             Value* operand = C->getOperand(j);
1592             printType(operand->getType());
1593             if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1594               gvs.insert(GV);
1595               if (GenerationType != GenFunction)
1596                 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1597                   if (GVar->hasInitializer())
1598                     consts.insert(GVar->getInitializer());
1599             }
1600           }
1601         }
1602       }
1603     }
1604   }
1605
1606   // Print the function declarations for any functions encountered
1607   nl(Out) << "// Function Declarations"; nl(Out);
1608   for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1609        I != E; ++I) {
1610     if (Function* Fun = dyn_cast<Function>(*I)) {
1611       if (!is_inline || Fun != F)
1612         printFunctionHead(Fun);
1613     }
1614   }
1615
1616   // Print the global variable declarations for any variables encountered
1617   nl(Out) << "// Global Variable Declarations"; nl(Out);
1618   for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1619        I != E; ++I) {
1620     if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1621       printVariableHead(F);
1622   }
1623
1624   // Print the constants found
1625   nl(Out) << "// Constant Definitions"; nl(Out);
1626   for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1627          E = consts.end(); I != E; ++I) {
1628     printConstant(*I);
1629   }
1630
1631   // Process the global variables definitions now that all the constants have
1632   // been emitted. These definitions just couple the gvars with their constant
1633   // initializers.
1634   if (GenerationType != GenFunction) {
1635     nl(Out) << "// Global Variable Definitions"; nl(Out);
1636     for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1637          I != E; ++I) {
1638       if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1639         printVariableBody(GV);
1640     }
1641   }
1642 }
1643
1644 void CppWriter::printFunctionHead(const Function* F) {
1645   nl(Out) << "Function* " << getCppName(F);
1646   Out << " = mod->getFunction(\"";
1647   printEscapedString(F->getName());
1648   Out << "\");";
1649   nl(Out) << "if (!" << getCppName(F) << ") {";
1650   nl(Out) << getCppName(F);
1651
1652   Out<< " = Function::Create(";
1653   nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1654   nl(Out) << "/*Linkage=*/";
1655   printLinkageType(F->getLinkage());
1656   Out << ",";
1657   nl(Out) << "/*Name=*/\"";
1658   printEscapedString(F->getName());
1659   Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1660   nl(Out,-1);
1661   printCppName(F);
1662   Out << "->setCallingConv(";
1663   printCallingConv(F->getCallingConv());
1664   Out << ");";
1665   nl(Out);
1666   if (F->hasSection()) {
1667     printCppName(F);
1668     Out << "->setSection(\"" << F->getSection() << "\");";
1669     nl(Out);
1670   }
1671   if (F->getAlignment()) {
1672     printCppName(F);
1673     Out << "->setAlignment(" << F->getAlignment() << ");";
1674     nl(Out);
1675   }
1676   if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1677     printCppName(F);
1678     Out << "->setVisibility(";
1679     printVisibilityType(F->getVisibility());
1680     Out << ");";
1681     nl(Out);
1682   }
1683   if (F->hasGC()) {
1684     printCppName(F);
1685     Out << "->setGC(\"" << F->getGC() << "\");";
1686     nl(Out);
1687   }
1688   Out << "}";
1689   nl(Out);
1690   printAttributes(F->getAttributes(), getCppName(F));
1691   printCppName(F);
1692   Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1693   nl(Out);
1694 }
1695
1696 void CppWriter::printFunctionBody(const Function *F) {
1697   if (F->isDeclaration())
1698     return; // external functions have no bodies.
1699
1700   // Clear the DefinedValues and ForwardRefs maps because we can't have
1701   // cross-function forward refs
1702   ForwardRefs.clear();
1703   DefinedValues.clear();
1704
1705   // Create all the argument values
1706   if (!is_inline) {
1707     if (!F->arg_empty()) {
1708       Out << "Function::arg_iterator args = " << getCppName(F)
1709           << "->arg_begin();";
1710       nl(Out);
1711     }
1712     for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1713          AI != AE; ++AI) {
1714       Out << "Value* " << getCppName(AI) << " = args++;";
1715       nl(Out);
1716       if (AI->hasName()) {
1717         Out << getCppName(AI) << "->setName(\"";
1718         printEscapedString(AI->getName());
1719         Out << "\");";
1720         nl(Out);
1721       }
1722     }
1723   }
1724
1725   // Create all the basic blocks
1726   nl(Out);
1727   for (Function::const_iterator BI = F->begin(), BE = F->end();
1728        BI != BE; ++BI) {
1729     std::string bbname(getCppName(BI));
1730     Out << "BasicBlock* " << bbname <<
1731            " = BasicBlock::Create(mod->getContext(), \"";
1732     if (BI->hasName())
1733       printEscapedString(BI->getName());
1734     Out << "\"," << getCppName(BI->getParent()) << ",0);";
1735     nl(Out);
1736   }
1737
1738   // Output all of its basic blocks... for the function
1739   for (Function::const_iterator BI = F->begin(), BE = F->end();
1740        BI != BE; ++BI) {
1741     std::string bbname(getCppName(BI));
1742     nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1743     nl(Out);
1744
1745     // Output all of the instructions in the basic block...
1746     for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1747          I != E; ++I) {
1748       printInstruction(I,bbname);
1749     }
1750   }
1751
1752   // Loop over the ForwardRefs and resolve them now that all instructions
1753   // are generated.
1754   if (!ForwardRefs.empty()) {
1755     nl(Out) << "// Resolve Forward References";
1756     nl(Out);
1757   }
1758
1759   while (!ForwardRefs.empty()) {
1760     ForwardRefMap::iterator I = ForwardRefs.begin();
1761     Out << I->second << "->replaceAllUsesWith("
1762         << getCppName(I->first) << "); delete " << I->second << ";";
1763     nl(Out);
1764     ForwardRefs.erase(I);
1765   }
1766 }
1767
1768 void CppWriter::printInline(const std::string& fname,
1769                             const std::string& func) {
1770   const Function* F = TheModule->getFunction(func);
1771   if (!F) {
1772     error(std::string("Function '") + func + "' not found in input module");
1773     return;
1774   }
1775   if (F->isDeclaration()) {
1776     error(std::string("Function '") + func + "' is external!");
1777     return;
1778   }
1779   nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1780           << getCppName(F);
1781   unsigned arg_count = 1;
1782   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1783        AI != AE; ++AI) {
1784     Out << ", Value* arg_" << arg_count;
1785   }
1786   Out << ") {";
1787   nl(Out);
1788   is_inline = true;
1789   printFunctionUses(F);
1790   printFunctionBody(F);
1791   is_inline = false;
1792   Out << "return " << getCppName(F->begin()) << ";";
1793   nl(Out) << "}";
1794   nl(Out);
1795 }
1796
1797 void CppWriter::printModuleBody() {
1798   // Print out all the type definitions
1799   nl(Out) << "// Type Definitions"; nl(Out);
1800   printTypes(TheModule);
1801
1802   // Functions can call each other and global variables can reference them so
1803   // define all the functions first before emitting their function bodies.
1804   nl(Out) << "// Function Declarations"; nl(Out);
1805   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1806        I != E; ++I)
1807     printFunctionHead(I);
1808
1809   // Process the global variables declarations. We can't initialze them until
1810   // after the constants are printed so just print a header for each global
1811   nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1812   for (Module::const_global_iterator I = TheModule->global_begin(),
1813          E = TheModule->global_end(); I != E; ++I) {
1814     printVariableHead(I);
1815   }
1816
1817   // Print out all the constants definitions. Constants don't recurse except
1818   // through GlobalValues. All GlobalValues have been declared at this point
1819   // so we can proceed to generate the constants.
1820   nl(Out) << "// Constant Definitions"; nl(Out);
1821   printConstants(TheModule);
1822
1823   // Process the global variables definitions now that all the constants have
1824   // been emitted. These definitions just couple the gvars with their constant
1825   // initializers.
1826   nl(Out) << "// Global Variable Definitions"; nl(Out);
1827   for (Module::const_global_iterator I = TheModule->global_begin(),
1828          E = TheModule->global_end(); I != E; ++I) {
1829     printVariableBody(I);
1830   }
1831
1832   // Finally, we can safely put out all of the function bodies.
1833   nl(Out) << "// Function Definitions"; nl(Out);
1834   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1835        I != E; ++I) {
1836     if (!I->isDeclaration()) {
1837       nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1838               << ")";
1839       nl(Out) << "{";
1840       nl(Out,1);
1841       printFunctionBody(I);
1842       nl(Out,-1) << "}";
1843       nl(Out);
1844     }
1845   }
1846 }
1847
1848 void CppWriter::printProgram(const std::string& fname,
1849                              const std::string& mName) {
1850   Out << "#include <llvm/LLVMContext.h>\n";
1851   Out << "#include <llvm/Module.h>\n";
1852   Out << "#include <llvm/DerivedTypes.h>\n";
1853   Out << "#include <llvm/Constants.h>\n";
1854   Out << "#include <llvm/GlobalVariable.h>\n";
1855   Out << "#include <llvm/Function.h>\n";
1856   Out << "#include <llvm/CallingConv.h>\n";
1857   Out << "#include <llvm/BasicBlock.h>\n";
1858   Out << "#include <llvm/Instructions.h>\n";
1859   Out << "#include <llvm/InlineAsm.h>\n";
1860   Out << "#include <llvm/Support/FormattedStream.h>\n";
1861   Out << "#include <llvm/Support/MathExtras.h>\n";
1862   Out << "#include <llvm/Pass.h>\n";
1863   Out << "#include <llvm/PassManager.h>\n";
1864   Out << "#include <llvm/ADT/SmallVector.h>\n";
1865   Out << "#include <llvm/Analysis/Verifier.h>\n";
1866   Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1867   Out << "#include <algorithm>\n";
1868   Out << "using namespace llvm;\n\n";
1869   Out << "Module* " << fname << "();\n\n";
1870   Out << "int main(int argc, char**argv) {\n";
1871   Out << "  Module* Mod = " << fname << "();\n";
1872   Out << "  verifyModule(*Mod, PrintMessageAction);\n";
1873   Out << "  PassManager PM;\n";
1874   Out << "  PM.add(createPrintModulePass(&outs()));\n";
1875   Out << "  PM.run(*Mod);\n";
1876   Out << "  return 0;\n";
1877   Out << "}\n\n";
1878   printModule(fname,mName);
1879 }
1880
1881 void CppWriter::printModule(const std::string& fname,
1882                             const std::string& mName) {
1883   nl(Out) << "Module* " << fname << "() {";
1884   nl(Out,1) << "// Module Construction";
1885   nl(Out) << "Module* mod = new Module(\"";
1886   printEscapedString(mName);
1887   Out << "\", getGlobalContext());";
1888   if (!TheModule->getTargetTriple().empty()) {
1889     nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1890   }
1891   if (!TheModule->getTargetTriple().empty()) {
1892     nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1893             << "\");";
1894   }
1895
1896   if (!TheModule->getModuleInlineAsm().empty()) {
1897     nl(Out) << "mod->setModuleInlineAsm(\"";
1898     printEscapedString(TheModule->getModuleInlineAsm());
1899     Out << "\");";
1900   }
1901   nl(Out);
1902
1903   // Loop over the dependent libraries and emit them.
1904   Module::lib_iterator LI = TheModule->lib_begin();
1905   Module::lib_iterator LE = TheModule->lib_end();
1906   while (LI != LE) {
1907     Out << "mod->addLibrary(\"" << *LI << "\");";
1908     nl(Out);
1909     ++LI;
1910   }
1911   printModuleBody();
1912   nl(Out) << "return mod;";
1913   nl(Out,-1) << "}";
1914   nl(Out);
1915 }
1916
1917 void CppWriter::printContents(const std::string& fname,
1918                               const std::string& mName) {
1919   Out << "\nModule* " << fname << "(Module *mod) {\n";
1920   Out << "\nmod->setModuleIdentifier(\"";
1921   printEscapedString(mName);
1922   Out << "\");\n";
1923   printModuleBody();
1924   Out << "\nreturn mod;\n";
1925   Out << "\n}\n";
1926 }
1927
1928 void CppWriter::printFunction(const std::string& fname,
1929                               const std::string& funcName) {
1930   const Function* F = TheModule->getFunction(funcName);
1931   if (!F) {
1932     error(std::string("Function '") + funcName + "' not found in input module");
1933     return;
1934   }
1935   Out << "\nFunction* " << fname << "(Module *mod) {\n";
1936   printFunctionUses(F);
1937   printFunctionHead(F);
1938   printFunctionBody(F);
1939   Out << "return " << getCppName(F) << ";\n";
1940   Out << "}\n";
1941 }
1942
1943 void CppWriter::printFunctions() {
1944   const Module::FunctionListType &funcs = TheModule->getFunctionList();
1945   Module::const_iterator I  = funcs.begin();
1946   Module::const_iterator IE = funcs.end();
1947
1948   for (; I != IE; ++I) {
1949     const Function &func = *I;
1950     if (!func.isDeclaration()) {
1951       std::string name("define_");
1952       name += func.getName();
1953       printFunction(name, func.getName());
1954     }
1955   }
1956 }
1957
1958 void CppWriter::printVariable(const std::string& fname,
1959                               const std::string& varName) {
1960   const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1961
1962   if (!GV) {
1963     error(std::string("Variable '") + varName + "' not found in input module");
1964     return;
1965   }
1966   Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1967   printVariableUses(GV);
1968   printVariableHead(GV);
1969   printVariableBody(GV);
1970   Out << "return " << getCppName(GV) << ";\n";
1971   Out << "}\n";
1972 }
1973
1974 void CppWriter::printType(const std::string &fname,
1975                           const std::string &typeName) {
1976   Type* Ty = TheModule->getTypeByName(typeName);
1977   if (!Ty) {
1978     error(std::string("Type '") + typeName + "' not found in input module");
1979     return;
1980   }
1981   Out << "\nType* " << fname << "(Module *mod) {\n";
1982   printType(Ty);
1983   Out << "return " << getCppName(Ty) << ";\n";
1984   Out << "}\n";
1985 }
1986
1987 bool CppWriter::runOnModule(Module &M) {
1988   TheModule = &M;
1989
1990   // Emit a header
1991   Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1992
1993   // Get the name of the function we're supposed to generate
1994   std::string fname = FuncName.getValue();
1995
1996   // Get the name of the thing we are to generate
1997   std::string tgtname = NameToGenerate.getValue();
1998   if (GenerationType == GenModule ||
1999       GenerationType == GenContents ||
2000       GenerationType == GenProgram ||
2001       GenerationType == GenFunctions) {
2002     if (tgtname == "!bad!") {
2003       if (M.getModuleIdentifier() == "-")
2004         tgtname = "<stdin>";
2005       else
2006         tgtname = M.getModuleIdentifier();
2007     }
2008   } else if (tgtname == "!bad!")
2009     error("You must use the -for option with -gen-{function,variable,type}");
2010
2011   switch (WhatToGenerate(GenerationType)) {
2012    case GenProgram:
2013     if (fname.empty())
2014       fname = "makeLLVMModule";
2015     printProgram(fname,tgtname);
2016     break;
2017    case GenModule:
2018     if (fname.empty())
2019       fname = "makeLLVMModule";
2020     printModule(fname,tgtname);
2021     break;
2022    case GenContents:
2023     if (fname.empty())
2024       fname = "makeLLVMModuleContents";
2025     printContents(fname,tgtname);
2026     break;
2027    case GenFunction:
2028     if (fname.empty())
2029       fname = "makeLLVMFunction";
2030     printFunction(fname,tgtname);
2031     break;
2032    case GenFunctions:
2033     printFunctions();
2034     break;
2035    case GenInline:
2036     if (fname.empty())
2037       fname = "makeLLVMInline";
2038     printInline(fname,tgtname);
2039     break;
2040    case GenVariable:
2041     if (fname.empty())
2042       fname = "makeLLVMVariable";
2043     printVariable(fname,tgtname);
2044     break;
2045    case GenType:
2046     if (fname.empty())
2047       fname = "makeLLVMType";
2048     printType(fname,tgtname);
2049     break;
2050   }
2051
2052   return false;
2053 }
2054
2055 char CppWriter::ID = 0;
2056
2057 //===----------------------------------------------------------------------===//
2058 //                       External Interface declaration
2059 //===----------------------------------------------------------------------===//
2060
2061 bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2062                                            formatted_raw_ostream &o,
2063                                            CodeGenFileType FileType,
2064                                            bool DisableVerify) {
2065   if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
2066   PM.add(new CppWriter(o));
2067   return false;
2068 }