blob: 3003a02064bcf94e11d626df2283c23055b4d6ee [file] [log] [blame]
Chris Lattner3af3ba82002-05-09 21:31:18 +00001//===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002//
3// This library implements the functionality defined in llvm/Assembly/CWriter.h
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00004//
5// TODO : Recursive types.
Chris Lattner16c7bb22002-05-09 02:28:59 +00006//
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00007//===-----------------------------------------------------------------------==//
Chris Lattner16c7bb22002-05-09 02:28:59 +00008
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00009#include "llvm/Assembly/CWriter.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000010#include "llvm/Constants.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000011#include "llvm/DerivedTypes.h"
12#include "llvm/Module.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000013#include "llvm/GlobalVariable.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000014#include "llvm/Function.h"
15#include "llvm/Argument.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000016#include "llvm/BasicBlock.h"
17#include "llvm/iMemory.h"
18#include "llvm/iTerminators.h"
19#include "llvm/iPHINode.h"
20#include "llvm/iOther.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000021#include "llvm/iOperators.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000022#include "llvm/SymbolTable.h"
Chris Lattner3af3ba82002-05-09 21:31:18 +000023#include "llvm/SlotCalculator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000024#include "llvm/Support/InstVisitor.h"
Chris Lattner7683a122002-05-09 20:33:35 +000025#include "llvm/Support/InstIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000026#include "Support/StringExtras.h"
27#include "Support/STLExtras.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000028#include <algorithm>
Chris Lattner78771c82002-05-17 04:55:35 +000029#include <set>
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000030using std::string;
31using std::map;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000032using std::ostream;
33
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000034static std::string getConstStrValue(const Constant* CPV);
35
36
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000037static std::string getConstArrayStrValue(const Constant* CPV) {
38 std::string Result;
39
40 // As a special case, print the array as a string if it is an array of
41 // ubytes or an array of sbytes with positive values.
42 //
43 const Type *ETy = cast<ArrayType>(CPV->getType())->getElementType();
44 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
45
Chris Lattner4fbf26d2002-05-09 20:53:56 +000046 // Make sure the last character is a null char, as automatically added by C
47 if (CPV->getNumOperands() == 0 ||
48 !cast<Constant>(*(CPV->op_end()-1))->isNullValue())
49 isString = false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000050
51 if (isString) {
52 Result = "\"";
Chris Lattner2f5eb4e2002-05-09 03:56:52 +000053 // Do not include the last character, which we know is null
54 for (unsigned i = 0, e = CPV->getNumOperands()-1; i != e; ++i) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000055 unsigned char C = (ETy == Type::SByteTy) ?
56 (unsigned char)cast<ConstantSInt>(CPV->getOperand(i))->getValue() :
57 (unsigned char)cast<ConstantUInt>(CPV->getOperand(i))->getValue();
58
59 if (isprint(C)) {
60 Result += C;
61 } else {
Chris Lattner2f5eb4e2002-05-09 03:56:52 +000062 switch (C) {
63 case '\n': Result += "\\n"; break;
64 case '\t': Result += "\\t"; break;
65 case '\r': Result += "\\r"; break;
66 case '\v': Result += "\\v"; break;
67 case '\a': Result += "\\a"; break;
68 default:
69 Result += "\\x";
70 Result += ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
71 Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
72 break;
73 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000074 }
75 }
76 Result += "\"";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000077 } else {
78 Result = "{";
79 if (CPV->getNumOperands()) {
80 Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
81 for (unsigned i = 1; i < CPV->getNumOperands(); i++)
82 Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
83 }
84 Result += " }";
85 }
86
87 return Result;
88}
89
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000090static std::string getConstStrValue(const Constant* CPV) {
Chris Lattner3ef6dc72002-05-09 14:40:11 +000091 switch (CPV->getType()->getPrimitiveID()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +000092 case Type::BoolTyID: return CPV == ConstantBool::False ? "0" : "1";
Chris Lattner3ef6dc72002-05-09 14:40:11 +000093 case Type::SByteTyID:
94 case Type::ShortTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +000095 case Type::IntTyID: return itostr(cast<ConstantSInt>(CPV)->getValue());
96 case Type::LongTyID: return itostr(cast<ConstantSInt>(CPV)->getValue())+"ll";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000097
Chris Lattner3ef6dc72002-05-09 14:40:11 +000098 case Type::UByteTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +000099 case Type::UShortTyID:return utostr(cast<ConstantUInt>(CPV)->getValue());
100 case Type::UIntTyID: return utostr(cast<ConstantUInt>(CPV)->getValue())+"u";
101 case Type::ULongTyID:return utostr(cast<ConstantUInt>(CPV)->getValue())+"ull";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000102
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000103 case Type::FloatTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000104 case Type::DoubleTyID: return ftostr(cast<ConstantFP>(CPV)->getValue());
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000105
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000106 case Type::ArrayTyID: return getConstArrayStrValue(CPV);
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000107
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000108 case Type::StructTyID: {
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000109 std::string Result = "{";
110 if (CPV->getNumOperands()) {
111 Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
112 for (unsigned i = 1; i < CPV->getNumOperands(); i++)
113 Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000114 }
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000115 return Result + " }";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000116 }
117
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000118 default:
119 cerr << "Unknown constant type: " << CPV << "\n";
120 abort();
121 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000122}
123
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000124// Pass the Type* variable and and the variable name and this prints out the
125// variable declaration.
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000126//
Chris Lattner16c7bb22002-05-09 02:28:59 +0000127static string calcTypeNameVar(const Type *Ty,
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000128 map<const Type *, string> &TypeNames,
129 const string &NameSoFar, bool ignoreName = false){
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000130 if (Ty->isPrimitiveType())
131 switch (Ty->getPrimitiveID()) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000132 case Type::VoidTyID: return "void " + NameSoFar;
133 case Type::BoolTyID: return "bool " + NameSoFar;
134 case Type::UByteTyID: return "unsigned char " + NameSoFar;
135 case Type::SByteTyID: return "signed char " + NameSoFar;
136 case Type::UShortTyID: return "unsigned short " + NameSoFar;
137 case Type::ShortTyID: return "short " + NameSoFar;
138 case Type::UIntTyID: return "unsigned " + NameSoFar;
139 case Type::IntTyID: return "int " + NameSoFar;
140 case Type::ULongTyID: return "unsigned long long " + NameSoFar;
141 case Type::LongTyID: return "signed long long " + NameSoFar;
Chris Lattner1f02c892002-05-09 20:14:10 +0000142 case Type::FloatTyID: return "float " + NameSoFar;
143 case Type::DoubleTyID: return "double " + NameSoFar;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000144 default :
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000145 cerr << "Unknown primitive type: " << Ty << "\n";
146 abort();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000147 }
148
149 // Check to see if the type is named.
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000150 if (!ignoreName) {
151 map<const Type *, string>::iterator I = TypeNames.find(Ty);
152 if (I != TypeNames.end())
153 return I->second + " " + NameSoFar;
154 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000155
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000156 string Result;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000157 switch (Ty->getPrimitiveID()) {
158 case Type::FunctionTyID: {
Chris Lattner7683a122002-05-09 20:33:35 +0000159 const FunctionType *MTy = cast<FunctionType>(Ty);
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000160 Result += calcTypeNameVar(MTy->getReturnType(), TypeNames, "");
Chris Lattner7683a122002-05-09 20:33:35 +0000161 Result += " " + NameSoFar + " (";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000162 for (FunctionType::ParamTypes::const_iterator
163 I = MTy->getParamTypes().begin(),
164 E = MTy->getParamTypes().end(); I != E; ++I) {
165 if (I != MTy->getParamTypes().begin())
166 Result += ", ";
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000167 Result += calcTypeNameVar(*I, TypeNames, "");
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000168 }
169 if (MTy->isVarArg()) {
170 if (!MTy->getParamTypes().empty())
171 Result += ", ";
172 Result += "...";
173 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000174 return Result + ")";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000175 }
176 case Type::StructTyID: {
177 const StructType *STy = cast<const StructType>(Ty);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000178 Result = NameSoFar + " {\n";
179 unsigned indx = 0;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000180 for (StructType::ElementTypes::const_iterator
181 I = STy->getElementTypes().begin(),
182 E = STy->getElementTypes().end(); I != E; ++I) {
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000183 Result += " " +calcTypeNameVar(*I, TypeNames, "field" + utostr(indx++));
184 Result += ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000185 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000186 return Result + "}";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000187 }
188
Chris Lattner3af3ba82002-05-09 21:31:18 +0000189 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000190 return calcTypeNameVar(cast<const PointerType>(Ty)->getElementType(),
191 TypeNames, "*" + NameSoFar);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000192
193 case Type::ArrayTyID: {
194 const ArrayType *ATy = cast<const ArrayType>(Ty);
195 int NumElements = ATy->getNumElements();
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000196 return calcTypeNameVar(ATy->getElementType(), TypeNames,
197 NameSoFar + "[" + itostr(NumElements) + "]");
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000198 }
199 default:
200 assert(0 && "Unhandled case in getTypeProps!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000201 abort();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000202 }
203
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000204 return Result;
205}
206
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000207namespace {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000208 class CWriter : public InstVisitor<CWriter> {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000209 ostream& Out;
210 SlotCalculator &Table;
211 const Module *TheModule;
212 map<const Type *, string> TypeNames;
Chris Lattner78771c82002-05-17 04:55:35 +0000213 std::set<const Value*> MangledGlobals;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000214 public:
215 inline CWriter(ostream &o, SlotCalculator &Tab, const Module *M)
216 : Out(o), Table(Tab), TheModule(M) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000217 }
218
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000219 inline void write(Module *M) { printModule(M); }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000220
Chris Lattner3af3ba82002-05-09 21:31:18 +0000221 ostream& printType(const Type *Ty, const string &VariableName = "") {
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000222 return Out << calcTypeNameVar(Ty, TypeNames, VariableName);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000223 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000224
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000225 void writeOperand(const Value *Operand);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000226 void writeOperandInternal(const Value *Operand);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000227
228 string getValueName(const Value *V);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000229
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000230 private :
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000231 void printModule(Module *M);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000232 void printSymbolTable(const SymbolTable &ST);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000233 void printGlobal(const GlobalVariable *GV);
Chris Lattner16c7bb22002-05-09 02:28:59 +0000234 void printFunctionSignature(const Function *F);
235 void printFunctionDecl(const Function *F); // Print just the forward decl
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000236
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000237 void printFunction(Function *);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000238
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000239 // isInlinableInst - Attempt to inline instructions into their uses to build
240 // trees as much as possible. To do this, we have to consistently decide
241 // what is acceptable to inline, so that variable declarations don't get
242 // printed and an extra copy of the expr is not emitted.
243 //
244 static bool isInlinableInst(Instruction *I) {
245 // Must be an expression, must be used exactly once. If it is dead, we
246 // emit it inline where it would go.
247 if (I->getType() == Type::VoidTy || I->use_size() != 1 ||
248 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I))
249 return false;
250
251 // Only inline instruction it it's use is in the same BB as the inst.
252 return I->getParent() == cast<Instruction>(I->use_back())->getParent();
253 }
254
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000255 // Instruction visitation functions
256 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000257
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000258 void visitReturnInst(ReturnInst *I);
259 void visitBranchInst(BranchInst *I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000260
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000261 void visitPHINode(PHINode *I) {}
262 void visitNot(GenericUnaryInst *I);
263 void visitBinaryOperator(Instruction *I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000264
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000265 void visitCastInst(CastInst *I);
266 void visitCallInst(CallInst *I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000267 void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000268
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000269 void visitMallocInst(MallocInst *I);
270 void visitAllocaInst(AllocaInst *I);
271 void visitFreeInst(FreeInst *I);
272 void visitLoadInst(LoadInst *I);
273 void visitStoreInst(StoreInst *I);
274 void visitGetElementPtrInst(GetElementPtrInst *I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000275
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000276 void visitInstruction(Instruction *I) {
277 cerr << "C Writer does not know about " << I;
278 abort();
279 }
280
281 void outputLValue(Instruction *I) {
282 Out << " " << getValueName(I) << " = ";
283 }
284 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
285 unsigned Indent);
286 void printIndexingExpr(MemAccessInst *MAI);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000287 };
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000288}
289
Chris Lattner2f499022002-05-09 04:21:21 +0000290// We dont want identifier names with ., space, - in them.
291// So we replace them with _
292static string makeNameProper(string x) {
293 string tmp;
294 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
295 switch (*sI) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000296 case '.': tmp += "d_"; break;
297 case ' ': tmp += "s_"; break;
298 case '-': tmp += "D_"; break;
Chris Lattner2f499022002-05-09 04:21:21 +0000299 default: tmp += *sI;
300 }
301
302 return tmp;
303}
304
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000305string CWriter::getValueName(const Value *V) {
Chris Lattner2f499022002-05-09 04:21:21 +0000306 if (V->hasName()) { // Print out the label if it exists...
Chris Lattner78771c82002-05-17 04:55:35 +0000307 if (isa<GlobalValue>(V) && // Do not mangle globals...
308 !MangledGlobals.count(V)) // Unless the name would collide unless we do.
Chris Lattner2f499022002-05-09 04:21:21 +0000309 return makeNameProper(V->getName());
310
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000311 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
312 makeNameProper(V->getName());
Chris Lattner2f499022002-05-09 04:21:21 +0000313 }
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000314
315 int Slot = Table.getValSlot(V);
316 assert(Slot >= 0 && "Invalid value!");
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000317 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000318}
319
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000320void CWriter::writeOperandInternal(const Value *Operand) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000321 if (Operand->hasName()) {
322 Out << getValueName(Operand);
323 } else if (const Constant *CPV = dyn_cast<const Constant>(Operand)) {
324 if (isa<ConstantPointerNull>(CPV)) {
325 Out << "((";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000326 printType(CPV->getType(), "");
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000327 Out << ")NULL)";
328 } else
329 Out << getConstStrValue(CPV);
330 } else {
331 int Slot = Table.getValSlot(Operand);
332 assert(Slot >= 0 && "Malformed LLVM!");
333 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
334 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000335}
336
337void CWriter::writeOperand(const Value *Operand) {
338 if (Instruction *I = dyn_cast<Instruction>(Operand))
339 if (isInlinableInst(I)) {
340 // Should we inline this instruction to build a tree?
341 Out << "(";
342 visit(I);
343 Out << ")";
344 return;
345 }
346
347 if (isa<GlobalVariable>(Operand))
348 Out << "(&"; // Global variables are references as their addresses by llvm
349
350 writeOperandInternal(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000351
352 if (isa<GlobalVariable>(Operand))
353 Out << ")";
354}
355
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000356void CWriter::printModule(Module *M) {
Chris Lattner78771c82002-05-17 04:55:35 +0000357 // Calculate which global values have names that will collide when we throw
358 // away type information.
359 { // Scope to declare the FoundNames set when we are done with it...
360 std::set<string> FoundNames;
361 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
362 if ((*I)->hasName()) // If the global has a name...
363 if (FoundNames.count((*I)->getName())) // And the name is already used
364 MangledGlobals.insert(*I); // Mangle the name
365 else
366 FoundNames.insert((*I)->getName()); // Otherwise, keep track of name
367
368 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
369 if ((*I)->hasName()) // If the global has a name...
370 if (FoundNames.count((*I)->getName())) // And the name is already used
371 MangledGlobals.insert(*I); // Mangle the name
372 else
373 FoundNames.insert((*I)->getName()); // Otherwise, keep track of name
374 }
375
376
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000377 // printing stdlib inclusion
378 // Out << "#include <stdlib.h>\n";
379
Chris Lattner16c7bb22002-05-09 02:28:59 +0000380 // get declaration for alloca
381 Out << "/* Provide Declarations */\n"
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000382 << "#include <alloca.h>\n\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000383
384 // Provide a definition for null if one does not already exist.
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000385 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000386 << "typedef unsigned char bool;\n"
387
388 << "\n\n/* Global Symbols */\n";
389
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000390 // Loop over the symbol table, emitting all named constants...
391 if (M->hasSymbolTable())
392 printSymbolTable(*M->getSymbolTable());
393
Chris Lattner16c7bb22002-05-09 02:28:59 +0000394 Out << "\n\n/* Global Data */\n";
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000395 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
396 GlobalVariable *GV = *I;
397 if (GV->hasInternalLinkage()) Out << "static ";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000398 printType(GV->getType()->getElementType(), getValueName(GV));
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000399
400 if (GV->hasInitializer()) {
401 Out << " = " ;
402 writeOperand(GV->getInitializer());
403 }
404 Out << ";\n";
405 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000406
Chris Lattner16c7bb22002-05-09 02:28:59 +0000407 // First output all the declarations of the functions as C requires Functions
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000408 // be declared before they are used.
Chris Lattner16c7bb22002-05-09 02:28:59 +0000409 //
410 Out << "\n\n/* Function Declarations */\n";
411 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunctionDecl));
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000412
Chris Lattner16c7bb22002-05-09 02:28:59 +0000413 // Output all of the functions...
414 Out << "\n\n/* Function Bodies */\n";
415 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunction));
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000416}
417
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000418
419// printSymbolTable - Run through symbol table looking for named constants
420// if a named constant is found, emit it's declaration...
421// Assuming that symbol table has only types and constants.
422void CWriter::printSymbolTable(const SymbolTable &ST) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000423 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
424 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
425 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
426
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000427 for (; I != End; ++I)
428 if (const Type *Ty = dyn_cast<const StructType>(I->second)) {
429 string Name = "struct l_" + I->first;
430 Out << Name << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000431
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000432 TypeNames.insert(std::make_pair(Ty, Name));
433 }
434 }
435
436 Out << "\n";
437
438 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
439 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
440 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
441
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000442 for (; I != End; ++I) {
443 const Value *V = I->second;
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000444 if (const Type *Ty = dyn_cast<const Type>(V)) {
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000445 string Name = "l_" + I->first;
Chris Lattner1f02c892002-05-09 20:14:10 +0000446 if (isa<StructType>(Ty))
447 Name = "struct " + Name;
448 else
449 Out << "typedef ";
450
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000451 Out << calcTypeNameVar(Ty, TypeNames, Name, true) << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000452 }
453 }
454 }
455}
456
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000457
Chris Lattner16c7bb22002-05-09 02:28:59 +0000458// printFunctionDecl - Print function declaration
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000459//
Chris Lattner16c7bb22002-05-09 02:28:59 +0000460void CWriter::printFunctionDecl(const Function *F) {
461 printFunctionSignature(F);
462 Out << ";\n";
463}
464
465void CWriter::printFunctionSignature(const Function *F) {
466 if (F->hasInternalLinkage()) Out << "static ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000467
468 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +0000469 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000470
Chris Lattner16c7bb22002-05-09 02:28:59 +0000471 // Print out the return type and name...
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000472 printType(F->getReturnType());
Chris Lattner1f02c892002-05-09 20:14:10 +0000473 Out << getValueName(F) << "(";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000474
Chris Lattner16c7bb22002-05-09 02:28:59 +0000475 if (!F->isExternal()) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000476 if (!F->getArgumentList().empty()) {
Chris Lattner3af3ba82002-05-09 21:31:18 +0000477 printType(F->getArgumentList().front()->getType(),
478 getValueName(F->getArgumentList().front()));
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000479
480 for (Function::ArgumentListType::const_iterator
481 I = F->getArgumentList().begin()+1,
482 E = F->getArgumentList().end(); I != E; ++I) {
483 Out << ", ";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000484 printType((*I)->getType(), getValueName(*I));
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000485 }
486 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000487 } else {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000488 // Loop over the arguments, printing them...
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000489 for (FunctionType::ParamTypes::const_iterator I =
Chris Lattner16c7bb22002-05-09 02:28:59 +0000490 FT->getParamTypes().begin(),
491 E = FT->getParamTypes().end(); I != E; ++I) {
492 if (I != FT->getParamTypes().begin()) Out << ", ";
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000493 printType(*I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000494 }
495 }
496
497 // Finish printing arguments...
Chris Lattner16c7bb22002-05-09 02:28:59 +0000498 if (FT->isVarArg()) {
499 if (FT->getParamTypes().size()) Out << ", ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000500 Out << "..."; // Output varargs portion of signature!
501 }
Chris Lattner16c7bb22002-05-09 02:28:59 +0000502 Out << ")";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000503}
504
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000505
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000506void CWriter::printFunction(Function *F) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000507 if (F->isExternal()) return;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000508
Chris Lattnerf34ee812002-05-09 03:12:34 +0000509 Table.incorporateFunction(F);
510
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000511 printFunctionSignature(F);
512 Out << " {\n";
513
Chris Lattner497e19a2002-05-09 20:39:03 +0000514 // print local variable information for the function
Chris Lattner7683a122002-05-09 20:33:35 +0000515 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000516 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000517 Out << " ";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000518 printType((*I)->getType(), getValueName(*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000519 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000520 }
Chris Lattner16c7bb22002-05-09 02:28:59 +0000521
522 // print the basic blocks
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000523 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
524 BasicBlock *BB = *I, *Prev = I != F->begin() ? *(I-1) : 0;
525
526 // Don't print the label for the basic block if there are no uses, or if the
527 // only terminator use is the precessor basic block's terminator. We have
528 // to scan the use list because PHI nodes use basic blocks too but do not
529 // require a label to be generated.
530 //
531 bool NeedsLabel = false;
532 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
533 UI != UE; ++UI)
534 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
535 if (TI != Prev->getTerminator()) {
536 NeedsLabel = true;
537 break;
538 }
539
540 if (NeedsLabel) Out << getValueName(BB) << ":\n";
541
542 // Output all of the instructions in the basic block...
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000543 for (BasicBlock::iterator II = BB->begin(), E = BB->end()-1;
544 II != E; ++II) {
545 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
546 Instruction *I = *II;
547 if (I->getType() != Type::VoidTy)
548 outputLValue(I);
549 else
550 Out << " ";
551 visit(I);
552 Out << ";\n";
553 }
554 }
555
556 // Don't emit prefix or suffix for the terminator...
557 visit(BB->getTerminator());
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000558 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000559
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000560 Out << "}\n\n";
Chris Lattnerf34ee812002-05-09 03:12:34 +0000561 Table.purgeFunction();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000562}
563
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000564// Specific Instruction type classes... note that all of the casts are
565// neccesary because we use the instruction classes as opaque types...
566//
567void CWriter::visitReturnInst(ReturnInst *I) {
568 // Don't output a void return if this is the last basic block in the function
569 if (I->getNumOperands() == 0 &&
Chris Lattner963b70b2002-05-21 18:05:19 +0000570 *(I->getParent()->getParent()->end()-1) == I->getParent() &&
571 !I->getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000572 return;
Chris Lattner963b70b2002-05-21 18:05:19 +0000573 }
Chris Lattner44408262002-05-09 03:50:42 +0000574
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000575 Out << " return";
576 if (I->getNumOperands()) {
577 Out << " ";
578 writeOperand(I->getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000579 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000580 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000581}
582
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000583// Return true if BB1 immediately preceeds BB2.
584static bool BBFollowsBB(BasicBlock *BB1, BasicBlock *BB2) {
585 Function *F = BB1->getParent();
586 Function::iterator I = find(F->begin(), F->end(), BB1);
587 assert(I != F->end() && "BB not in function!");
588 return *(I+1) == BB2;
589}
590
591static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
592 // If PHI nodes need copies, we need the copy code...
593 if (isa<PHINode>(To->front()) ||
594 !BBFollowsBB(From, To)) // Not directly successor, need goto
595 return true;
596
597 // Otherwise we don't need the code.
598 return false;
599}
600
601void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
602 unsigned Indent) {
603 for (BasicBlock::iterator I = Succ->begin();
604 PHINode *PN = dyn_cast<PHINode>(*I); ++I) {
605 // now we have to do the printing
606 Out << string(Indent, ' ');
607 outputLValue(PN);
608 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
609 Out << "; /* for PHI node */\n";
610 }
611
612 if (!BBFollowsBB(CurBB, Succ)) {
613 Out << string(Indent, ' ') << " goto ";
614 writeOperand(Succ);
615 Out << ";\n";
616 }
617}
618
619// Brach instruction printing - Avoid printing out a brach to a basic block that
620// immediately succeeds the current one.
621//
622void CWriter::visitBranchInst(BranchInst *I) {
623 if (I->isConditional()) {
624 if (isGotoCodeNeccessary(I->getParent(), I->getSuccessor(0))) {
625 Out << " if (";
626 writeOperand(I->getCondition());
627 Out << ") {\n";
628
629 printBranchToBlock(I->getParent(), I->getSuccessor(0), 2);
630
631 if (isGotoCodeNeccessary(I->getParent(), I->getSuccessor(1))) {
632 Out << " } else {\n";
633 printBranchToBlock(I->getParent(), I->getSuccessor(1), 2);
634 }
635 } else {
636 // First goto not neccesary, assume second one is...
637 Out << " if (!";
638 writeOperand(I->getCondition());
639 Out << ") {\n";
640
641 printBranchToBlock(I->getParent(), I->getSuccessor(1), 2);
642 }
643
644 Out << " }\n";
645 } else {
646 printBranchToBlock(I->getParent(), I->getSuccessor(0), 0);
647 }
648 Out << "\n";
649}
650
651
652void CWriter::visitNot(GenericUnaryInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000653 Out << "~";
654 writeOperand(I->getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000655}
656
657void CWriter::visitBinaryOperator(Instruction *I) {
658 // binary instructions, shift instructions, setCond instructions.
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000659 if (isa<PointerType>(I->getType())) {
660 Out << "(";
661 printType(I->getType());
662 Out << ")";
663 }
664
665 if (isa<PointerType>(I->getType())) Out << "(long long)";
666 writeOperand(I->getOperand(0));
667
668 switch (I->getOpcode()) {
669 case Instruction::Add: Out << " + "; break;
670 case Instruction::Sub: Out << " - "; break;
671 case Instruction::Mul: Out << "*"; break;
672 case Instruction::Div: Out << "/"; break;
673 case Instruction::Rem: Out << "%"; break;
674 case Instruction::And: Out << " & "; break;
675 case Instruction::Or: Out << " | "; break;
676 case Instruction::Xor: Out << " ^ "; break;
677 case Instruction::SetEQ: Out << " == "; break;
678 case Instruction::SetNE: Out << " != "; break;
679 case Instruction::SetLE: Out << " <= "; break;
680 case Instruction::SetGE: Out << " >= "; break;
681 case Instruction::SetLT: Out << " < "; break;
682 case Instruction::SetGT: Out << " > "; break;
683 case Instruction::Shl : Out << " << "; break;
684 case Instruction::Shr : Out << " >> "; break;
685 default: cerr << "Invalid operator type!" << I; abort();
686 }
687
688 if (isa<PointerType>(I->getType())) Out << "(long long)";
689 writeOperand(I->getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000690}
691
692void CWriter::visitCastInst(CastInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000693 Out << "(";
694 printType(I->getType());
695 Out << ")";
696 writeOperand(I->getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000697}
698
699void CWriter::visitCallInst(CallInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000700 const PointerType *PTy = cast<PointerType>(I->getCalledValue()->getType());
701 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
702 const Type *RetTy = FTy->getReturnType();
703
704 Out << getValueName(I->getOperand(0)) << "(";
705
706 if (I->getNumOperands() > 1) {
707 writeOperand(I->getOperand(1));
708
709 for (unsigned op = 2, Eop = I->getNumOperands(); op != Eop; ++op) {
710 Out << ", ";
711 writeOperand(I->getOperand(op));
712 }
713 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000714 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000715}
716
717void CWriter::visitMallocInst(MallocInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000718 Out << "(";
719 printType(I->getType());
720 Out << ")malloc(sizeof(";
721 printType(I->getType()->getElementType());
722 Out << ")";
723
724 if (I->isArrayAllocation()) {
725 Out << " * " ;
726 writeOperand(I->getOperand(0));
727 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000728 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000729}
730
731void CWriter::visitAllocaInst(AllocaInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000732 Out << "(";
733 printType(I->getType());
734 Out << ") alloca(sizeof(";
735 printType(I->getType()->getElementType());
736 Out << ")";
737 if (I->isArrayAllocation()) {
738 Out << " * " ;
739 writeOperand(I->getOperand(0));
740 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000741 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000742}
743
744void CWriter::visitFreeInst(FreeInst *I) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000745 Out << "free(";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000746 writeOperand(I->getOperand(0));
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000747 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000748}
749
750void CWriter::printIndexingExpr(MemAccessInst *MAI) {
751 MemAccessInst::op_iterator I = MAI->idx_begin(), E = MAI->idx_end();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000752 if (I == E) {
753 // If accessing a global value with no indexing, avoid *(&GV) syndrome
754 if (GlobalValue *V = dyn_cast<GlobalValue>(MAI->getPointerOperand())) {
755 writeOperandInternal(V);
756 return;
757 }
758
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000759 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000760 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000761
762 writeOperand(MAI->getPointerOperand());
763
764 if (I == E) return;
765
766 // Print out the -> operator if possible...
767 Constant *CI = dyn_cast<Constant>(*I);
768 if (CI && CI->isNullValue() && I+1 != E &&
769 (*(I+1))->getType() == Type::UByteTy) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000770 Out << "->field" << cast<ConstantUInt>(*(I+1))->getValue();
771 I += 2;
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000772 }
773
774 for (; I != E; ++I)
775 if ((*I)->getType() == Type::UIntTy) {
776 Out << "[";
777 writeOperand(*I);
778 Out << "]";
779 } else {
780 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
781 }
782}
783
784void CWriter::visitLoadInst(LoadInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000785 printIndexingExpr(I);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000786}
787
788void CWriter::visitStoreInst(StoreInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000789 printIndexingExpr(I);
790 Out << " = ";
791 writeOperand(I->getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000792}
793
794void CWriter::visitGetElementPtrInst(GetElementPtrInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000795 Out << "&";
796 printIndexingExpr(I);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000797}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000798
799//===----------------------------------------------------------------------===//
800// External Interface declaration
801//===----------------------------------------------------------------------===//
802
Chris Lattnerf34ee812002-05-09 03:12:34 +0000803void WriteToC(const Module *M, ostream &Out) {
804 assert(M && "You can't write a null module!!");
805 SlotCalculator SlotTable(M, false);
806 CWriter W(Out, SlotTable, M);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000807 W.write((Module*)M);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000808 Out.flush();
809}