blob: 27199fe4400901432e9ec2ef7c1bafc8445e3090 [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>
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000029using std::string;
30using std::map;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000031using std::ostream;
32
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000033static std::string getConstStrValue(const Constant* CPV);
34
35
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000036static std::string getConstArrayStrValue(const Constant* CPV) {
37 std::string Result;
38
39 // As a special case, print the array as a string if it is an array of
40 // ubytes or an array of sbytes with positive values.
41 //
42 const Type *ETy = cast<ArrayType>(CPV->getType())->getElementType();
43 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
44
Chris Lattner4fbf26d2002-05-09 20:53:56 +000045 // Make sure the last character is a null char, as automatically added by C
46 if (CPV->getNumOperands() == 0 ||
47 !cast<Constant>(*(CPV->op_end()-1))->isNullValue())
48 isString = false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000049
50 if (isString) {
51 Result = "\"";
Chris Lattner2f5eb4e2002-05-09 03:56:52 +000052 // Do not include the last character, which we know is null
53 for (unsigned i = 0, e = CPV->getNumOperands()-1; i != e; ++i) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000054 unsigned char C = (ETy == Type::SByteTy) ?
55 (unsigned char)cast<ConstantSInt>(CPV->getOperand(i))->getValue() :
56 (unsigned char)cast<ConstantUInt>(CPV->getOperand(i))->getValue();
57
58 if (isprint(C)) {
59 Result += C;
60 } else {
Chris Lattner2f5eb4e2002-05-09 03:56:52 +000061 switch (C) {
62 case '\n': Result += "\\n"; break;
63 case '\t': Result += "\\t"; break;
64 case '\r': Result += "\\r"; break;
65 case '\v': Result += "\\v"; break;
66 case '\a': Result += "\\a"; break;
67 default:
68 Result += "\\x";
69 Result += ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
70 Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
71 break;
72 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000073 }
74 }
75 Result += "\"";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000076 } else {
77 Result = "{";
78 if (CPV->getNumOperands()) {
79 Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
80 for (unsigned i = 1; i < CPV->getNumOperands(); i++)
81 Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
82 }
83 Result += " }";
84 }
85
86 return Result;
87}
88
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000089static std::string getConstStrValue(const Constant* CPV) {
Chris Lattner3ef6dc72002-05-09 14:40:11 +000090 switch (CPV->getType()->getPrimitiveID()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +000091 case Type::BoolTyID: return CPV == ConstantBool::False ? "0" : "1";
Chris Lattner3ef6dc72002-05-09 14:40:11 +000092 case Type::SByteTyID:
93 case Type::ShortTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +000094 case Type::IntTyID: return itostr(cast<ConstantSInt>(CPV)->getValue());
95 case Type::LongTyID: return itostr(cast<ConstantSInt>(CPV)->getValue())+"ll";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000096
Chris Lattner3ef6dc72002-05-09 14:40:11 +000097 case Type::UByteTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +000098 case Type::UShortTyID:return utostr(cast<ConstantUInt>(CPV)->getValue());
99 case Type::UIntTyID: return utostr(cast<ConstantUInt>(CPV)->getValue())+"u";
100 case Type::ULongTyID:return utostr(cast<ConstantUInt>(CPV)->getValue())+"ull";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000101
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000102 case Type::FloatTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000103 case Type::DoubleTyID: return ftostr(cast<ConstantFP>(CPV)->getValue());
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000104
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000105 case Type::ArrayTyID: return getConstArrayStrValue(CPV);
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000106
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000107 case Type::StructTyID: {
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000108 std::string Result = "{";
109 if (CPV->getNumOperands()) {
110 Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
111 for (unsigned i = 1; i < CPV->getNumOperands(); i++)
112 Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000113 }
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000114 return Result + " }";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000115 }
116
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000117 default:
118 cerr << "Unknown constant type: " << CPV << "\n";
119 abort();
120 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000121}
122
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000123// Pass the Type* variable and and the variable name and this prints out the
124// variable declaration.
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000125//
Chris Lattner16c7bb22002-05-09 02:28:59 +0000126static string calcTypeNameVar(const Type *Ty,
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000127 map<const Type *, string> &TypeNames,
128 const string &NameSoFar, bool ignoreName = false){
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000129 if (Ty->isPrimitiveType())
130 switch (Ty->getPrimitiveID()) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000131 case Type::VoidTyID: return "void " + NameSoFar;
132 case Type::BoolTyID: return "bool " + NameSoFar;
133 case Type::UByteTyID: return "unsigned char " + NameSoFar;
134 case Type::SByteTyID: return "signed char " + NameSoFar;
135 case Type::UShortTyID: return "unsigned short " + NameSoFar;
136 case Type::ShortTyID: return "short " + NameSoFar;
137 case Type::UIntTyID: return "unsigned " + NameSoFar;
138 case Type::IntTyID: return "int " + NameSoFar;
139 case Type::ULongTyID: return "unsigned long long " + NameSoFar;
140 case Type::LongTyID: return "signed long long " + NameSoFar;
Chris Lattner1f02c892002-05-09 20:14:10 +0000141 case Type::FloatTyID: return "float " + NameSoFar;
142 case Type::DoubleTyID: return "double " + NameSoFar;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000143 default :
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000144 cerr << "Unknown primitive type: " << Ty << "\n";
145 abort();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000146 }
147
148 // Check to see if the type is named.
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000149 if (!ignoreName) {
150 map<const Type *, string>::iterator I = TypeNames.find(Ty);
151 if (I != TypeNames.end())
152 return I->second + " " + NameSoFar;
153 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000154
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000155 string Result;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000156 switch (Ty->getPrimitiveID()) {
157 case Type::FunctionTyID: {
Chris Lattner7683a122002-05-09 20:33:35 +0000158 const FunctionType *MTy = cast<FunctionType>(Ty);
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000159 Result += calcTypeNameVar(MTy->getReturnType(), TypeNames, "");
Chris Lattner7683a122002-05-09 20:33:35 +0000160 Result += " " + NameSoFar + " (";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000161 for (FunctionType::ParamTypes::const_iterator
162 I = MTy->getParamTypes().begin(),
163 E = MTy->getParamTypes().end(); I != E; ++I) {
164 if (I != MTy->getParamTypes().begin())
165 Result += ", ";
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000166 Result += calcTypeNameVar(*I, TypeNames, "");
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000167 }
168 if (MTy->isVarArg()) {
169 if (!MTy->getParamTypes().empty())
170 Result += ", ";
171 Result += "...";
172 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000173 return Result + ")";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000174 }
175 case Type::StructTyID: {
176 const StructType *STy = cast<const StructType>(Ty);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000177 Result = NameSoFar + " {\n";
178 unsigned indx = 0;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000179 for (StructType::ElementTypes::const_iterator
180 I = STy->getElementTypes().begin(),
181 E = STy->getElementTypes().end(); I != E; ++I) {
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000182 Result += " " +calcTypeNameVar(*I, TypeNames, "field" + utostr(indx++));
183 Result += ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000184 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000185 return Result + "}";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000186 }
187
Chris Lattner3af3ba82002-05-09 21:31:18 +0000188 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000189 return calcTypeNameVar(cast<const PointerType>(Ty)->getElementType(),
190 TypeNames, "*" + NameSoFar);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000191
192 case Type::ArrayTyID: {
193 const ArrayType *ATy = cast<const ArrayType>(Ty);
194 int NumElements = ATy->getNumElements();
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000195 return calcTypeNameVar(ATy->getElementType(), TypeNames,
196 NameSoFar + "[" + itostr(NumElements) + "]");
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000197 }
198 default:
199 assert(0 && "Unhandled case in getTypeProps!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000200 abort();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000201 }
202
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000203 return Result;
204}
205
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000206namespace {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000207 class CWriter : public InstVisitor<CWriter> {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000208 ostream& Out;
209 SlotCalculator &Table;
210 const Module *TheModule;
211 map<const Type *, string> TypeNames;
212 public:
213 inline CWriter(ostream &o, SlotCalculator &Tab, const Module *M)
214 : Out(o), Table(Tab), TheModule(M) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000215 }
216
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000217 inline void write(Module *M) { printModule(M); }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000218
Chris Lattner3af3ba82002-05-09 21:31:18 +0000219 ostream& printType(const Type *Ty, const string &VariableName = "") {
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000220 return Out << calcTypeNameVar(Ty, TypeNames, VariableName);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000221 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000222
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000223 void writeOperand(const Value *Operand);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000224 void writeOperandInternal(const Value *Operand);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000225
226 string getValueName(const Value *V);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000227
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000228 private :
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000229 void printModule(Module *M);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000230 void printSymbolTable(const SymbolTable &ST);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000231 void printGlobal(const GlobalVariable *GV);
Chris Lattner16c7bb22002-05-09 02:28:59 +0000232 void printFunctionSignature(const Function *F);
233 void printFunctionDecl(const Function *F); // Print just the forward decl
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000234
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000235 void printFunction(Function *);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000236
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000237 // isInlinableInst - Attempt to inline instructions into their uses to build
238 // trees as much as possible. To do this, we have to consistently decide
239 // what is acceptable to inline, so that variable declarations don't get
240 // printed and an extra copy of the expr is not emitted.
241 //
242 static bool isInlinableInst(Instruction *I) {
243 // Must be an expression, must be used exactly once. If it is dead, we
244 // emit it inline where it would go.
245 if (I->getType() == Type::VoidTy || I->use_size() != 1 ||
246 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I))
247 return false;
248
249 // Only inline instruction it it's use is in the same BB as the inst.
250 return I->getParent() == cast<Instruction>(I->use_back())->getParent();
251 }
252
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000253 // Instruction visitation functions
254 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000255
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000256 void visitReturnInst(ReturnInst *I);
257 void visitBranchInst(BranchInst *I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000258
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000259 void visitPHINode(PHINode *I) {}
260 void visitNot(GenericUnaryInst *I);
261 void visitBinaryOperator(Instruction *I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000262
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000263 void visitCastInst(CastInst *I);
264 void visitCallInst(CallInst *I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000265 void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000266
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000267 void visitMallocInst(MallocInst *I);
268 void visitAllocaInst(AllocaInst *I);
269 void visitFreeInst(FreeInst *I);
270 void visitLoadInst(LoadInst *I);
271 void visitStoreInst(StoreInst *I);
272 void visitGetElementPtrInst(GetElementPtrInst *I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000273
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000274 void visitInstruction(Instruction *I) {
275 cerr << "C Writer does not know about " << I;
276 abort();
277 }
278
279 void outputLValue(Instruction *I) {
280 Out << " " << getValueName(I) << " = ";
281 }
282 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
283 unsigned Indent);
284 void printIndexingExpr(MemAccessInst *MAI);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000285 };
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000286}
287
Chris Lattner2f499022002-05-09 04:21:21 +0000288// We dont want identifier names with ., space, - in them.
289// So we replace them with _
290static string makeNameProper(string x) {
291 string tmp;
292 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
293 switch (*sI) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000294 case '.': tmp += "d_"; break;
295 case ' ': tmp += "s_"; break;
296 case '-': tmp += "D_"; break;
Chris Lattner2f499022002-05-09 04:21:21 +0000297 case '_': tmp += "__"; break;
298 default: tmp += *sI;
299 }
300
301 return tmp;
302}
303
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000304string CWriter::getValueName(const Value *V) {
Chris Lattner2f499022002-05-09 04:21:21 +0000305 if (V->hasName()) { // Print out the label if it exists...
306 if (isa<GlobalValue>(V)) // Do not mangle globals...
307 return makeNameProper(V->getName());
308
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000309 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
310 makeNameProper(V->getName());
Chris Lattner2f499022002-05-09 04:21:21 +0000311 }
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000312
313 int Slot = Table.getValSlot(V);
314 assert(Slot >= 0 && "Invalid value!");
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000315 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000316}
317
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000318void CWriter::writeOperandInternal(const Value *Operand) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000319 if (Operand->hasName()) {
320 Out << getValueName(Operand);
321 } else if (const Constant *CPV = dyn_cast<const Constant>(Operand)) {
322 if (isa<ConstantPointerNull>(CPV)) {
323 Out << "((";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000324 printType(CPV->getType(), "");
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000325 Out << ")NULL)";
326 } else
327 Out << getConstStrValue(CPV);
328 } else {
329 int Slot = Table.getValSlot(Operand);
330 assert(Slot >= 0 && "Malformed LLVM!");
331 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
332 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000333}
334
335void CWriter::writeOperand(const Value *Operand) {
336 if (Instruction *I = dyn_cast<Instruction>(Operand))
337 if (isInlinableInst(I)) {
338 // Should we inline this instruction to build a tree?
339 Out << "(";
340 visit(I);
341 Out << ")";
342 return;
343 }
344
345 if (isa<GlobalVariable>(Operand))
346 Out << "(&"; // Global variables are references as their addresses by llvm
347
348 writeOperandInternal(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000349
350 if (isa<GlobalVariable>(Operand))
351 Out << ")";
352}
353
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000354void CWriter::printModule(Module *M) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000355 // printing stdlib inclusion
356 // Out << "#include <stdlib.h>\n";
357
Chris Lattner16c7bb22002-05-09 02:28:59 +0000358 // get declaration for alloca
359 Out << "/* Provide Declarations */\n"
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000360 << "#include <alloca.h>\n\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000361
362 // Provide a definition for null if one does not already exist.
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000363 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000364 << "typedef unsigned char bool;\n"
365
366 << "\n\n/* Global Symbols */\n";
367
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000368 // Loop over the symbol table, emitting all named constants...
369 if (M->hasSymbolTable())
370 printSymbolTable(*M->getSymbolTable());
371
Chris Lattner16c7bb22002-05-09 02:28:59 +0000372 Out << "\n\n/* Global Data */\n";
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000373 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
374 GlobalVariable *GV = *I;
375 if (GV->hasInternalLinkage()) Out << "static ";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000376 printType(GV->getType()->getElementType(), getValueName(GV));
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000377
378 if (GV->hasInitializer()) {
379 Out << " = " ;
380 writeOperand(GV->getInitializer());
381 }
382 Out << ";\n";
383 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000384
Chris Lattner16c7bb22002-05-09 02:28:59 +0000385 // First output all the declarations of the functions as C requires Functions
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000386 // be declared before they are used.
Chris Lattner16c7bb22002-05-09 02:28:59 +0000387 //
388 Out << "\n\n/* Function Declarations */\n";
389 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunctionDecl));
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000390
Chris Lattner16c7bb22002-05-09 02:28:59 +0000391 // Output all of the functions...
392 Out << "\n\n/* Function Bodies */\n";
393 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunction));
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000394}
395
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000396
397// printSymbolTable - Run through symbol table looking for named constants
398// if a named constant is found, emit it's declaration...
399// Assuming that symbol table has only types and constants.
400void CWriter::printSymbolTable(const SymbolTable &ST) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000401 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
402 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
403 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
404
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000405 for (; I != End; ++I)
406 if (const Type *Ty = dyn_cast<const StructType>(I->second)) {
407 string Name = "struct l_" + I->first;
408 Out << Name << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000409
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000410 TypeNames.insert(std::make_pair(Ty, Name));
411 }
412 }
413
414 Out << "\n";
415
416 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
417 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
418 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
419
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000420 for (; I != End; ++I) {
421 const Value *V = I->second;
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000422 if (const Type *Ty = dyn_cast<const Type>(V)) {
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000423 string Name = "l_" + I->first;
Chris Lattner1f02c892002-05-09 20:14:10 +0000424 if (isa<StructType>(Ty))
425 Name = "struct " + Name;
426 else
427 Out << "typedef ";
428
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000429 Out << calcTypeNameVar(Ty, TypeNames, Name, true) << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000430 }
431 }
432 }
433}
434
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000435
Chris Lattner16c7bb22002-05-09 02:28:59 +0000436// printFunctionDecl - Print function declaration
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000437//
Chris Lattner16c7bb22002-05-09 02:28:59 +0000438void CWriter::printFunctionDecl(const Function *F) {
439 printFunctionSignature(F);
440 Out << ";\n";
441}
442
443void CWriter::printFunctionSignature(const Function *F) {
444 if (F->hasInternalLinkage()) Out << "static ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000445
446 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +0000447 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000448
Chris Lattner16c7bb22002-05-09 02:28:59 +0000449 // Print out the return type and name...
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000450 printType(F->getReturnType());
Chris Lattner1f02c892002-05-09 20:14:10 +0000451 Out << getValueName(F) << "(";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000452
Chris Lattner16c7bb22002-05-09 02:28:59 +0000453 if (!F->isExternal()) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000454 if (!F->getArgumentList().empty()) {
Chris Lattner3af3ba82002-05-09 21:31:18 +0000455 printType(F->getArgumentList().front()->getType(),
456 getValueName(F->getArgumentList().front()));
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000457
458 for (Function::ArgumentListType::const_iterator
459 I = F->getArgumentList().begin()+1,
460 E = F->getArgumentList().end(); I != E; ++I) {
461 Out << ", ";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000462 printType((*I)->getType(), getValueName(*I));
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000463 }
464 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000465 } else {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000466 // Loop over the arguments, printing them...
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000467 for (FunctionType::ParamTypes::const_iterator I =
Chris Lattner16c7bb22002-05-09 02:28:59 +0000468 FT->getParamTypes().begin(),
469 E = FT->getParamTypes().end(); I != E; ++I) {
470 if (I != FT->getParamTypes().begin()) Out << ", ";
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000471 printType(*I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000472 }
473 }
474
475 // Finish printing arguments...
Chris Lattner16c7bb22002-05-09 02:28:59 +0000476 if (FT->isVarArg()) {
477 if (FT->getParamTypes().size()) Out << ", ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000478 Out << "..."; // Output varargs portion of signature!
479 }
Chris Lattner16c7bb22002-05-09 02:28:59 +0000480 Out << ")";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000481}
482
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000483
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000484void CWriter::printFunction(Function *F) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000485 if (F->isExternal()) return;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000486
Chris Lattnerf34ee812002-05-09 03:12:34 +0000487 Table.incorporateFunction(F);
488
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000489 printFunctionSignature(F);
490 Out << " {\n";
491
Chris Lattner497e19a2002-05-09 20:39:03 +0000492 // print local variable information for the function
Chris Lattner7683a122002-05-09 20:33:35 +0000493 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000494 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000495 Out << " ";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000496 printType((*I)->getType(), getValueName(*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000497 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000498 }
Chris Lattner16c7bb22002-05-09 02:28:59 +0000499
500 // print the basic blocks
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000501 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
502 BasicBlock *BB = *I, *Prev = I != F->begin() ? *(I-1) : 0;
503
504 // Don't print the label for the basic block if there are no uses, or if the
505 // only terminator use is the precessor basic block's terminator. We have
506 // to scan the use list because PHI nodes use basic blocks too but do not
507 // require a label to be generated.
508 //
509 bool NeedsLabel = false;
510 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
511 UI != UE; ++UI)
512 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
513 if (TI != Prev->getTerminator()) {
514 NeedsLabel = true;
515 break;
516 }
517
518 if (NeedsLabel) Out << getValueName(BB) << ":\n";
519
520 // Output all of the instructions in the basic block...
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000521 for (BasicBlock::iterator II = BB->begin(), E = BB->end()-1;
522 II != E; ++II) {
523 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
524 Instruction *I = *II;
525 if (I->getType() != Type::VoidTy)
526 outputLValue(I);
527 else
528 Out << " ";
529 visit(I);
530 Out << ";\n";
531 }
532 }
533
534 // Don't emit prefix or suffix for the terminator...
535 visit(BB->getTerminator());
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000536 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000537
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000538 Out << "}\n\n";
Chris Lattnerf34ee812002-05-09 03:12:34 +0000539 Table.purgeFunction();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000540}
541
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000542// Specific Instruction type classes... note that all of the casts are
543// neccesary because we use the instruction classes as opaque types...
544//
545void CWriter::visitReturnInst(ReturnInst *I) {
546 // Don't output a void return if this is the last basic block in the function
547 if (I->getNumOperands() == 0 &&
548 *(I->getParent()->getParent()->end()-1) == I->getParent())
549 return;
Chris Lattner44408262002-05-09 03:50:42 +0000550
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000551 Out << " return";
552 if (I->getNumOperands()) {
553 Out << " ";
554 writeOperand(I->getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000555 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000556 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000557}
558
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000559// Return true if BB1 immediately preceeds BB2.
560static bool BBFollowsBB(BasicBlock *BB1, BasicBlock *BB2) {
561 Function *F = BB1->getParent();
562 Function::iterator I = find(F->begin(), F->end(), BB1);
563 assert(I != F->end() && "BB not in function!");
564 return *(I+1) == BB2;
565}
566
567static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
568 // If PHI nodes need copies, we need the copy code...
569 if (isa<PHINode>(To->front()) ||
570 !BBFollowsBB(From, To)) // Not directly successor, need goto
571 return true;
572
573 // Otherwise we don't need the code.
574 return false;
575}
576
577void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
578 unsigned Indent) {
579 for (BasicBlock::iterator I = Succ->begin();
580 PHINode *PN = dyn_cast<PHINode>(*I); ++I) {
581 // now we have to do the printing
582 Out << string(Indent, ' ');
583 outputLValue(PN);
584 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
585 Out << "; /* for PHI node */\n";
586 }
587
588 if (!BBFollowsBB(CurBB, Succ)) {
589 Out << string(Indent, ' ') << " goto ";
590 writeOperand(Succ);
591 Out << ";\n";
592 }
593}
594
595// Brach instruction printing - Avoid printing out a brach to a basic block that
596// immediately succeeds the current one.
597//
598void CWriter::visitBranchInst(BranchInst *I) {
599 if (I->isConditional()) {
600 if (isGotoCodeNeccessary(I->getParent(), I->getSuccessor(0))) {
601 Out << " if (";
602 writeOperand(I->getCondition());
603 Out << ") {\n";
604
605 printBranchToBlock(I->getParent(), I->getSuccessor(0), 2);
606
607 if (isGotoCodeNeccessary(I->getParent(), I->getSuccessor(1))) {
608 Out << " } else {\n";
609 printBranchToBlock(I->getParent(), I->getSuccessor(1), 2);
610 }
611 } else {
612 // First goto not neccesary, assume second one is...
613 Out << " if (!";
614 writeOperand(I->getCondition());
615 Out << ") {\n";
616
617 printBranchToBlock(I->getParent(), I->getSuccessor(1), 2);
618 }
619
620 Out << " }\n";
621 } else {
622 printBranchToBlock(I->getParent(), I->getSuccessor(0), 0);
623 }
624 Out << "\n";
625}
626
627
628void CWriter::visitNot(GenericUnaryInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000629 Out << "~";
630 writeOperand(I->getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000631}
632
633void CWriter::visitBinaryOperator(Instruction *I) {
634 // binary instructions, shift instructions, setCond instructions.
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000635 if (isa<PointerType>(I->getType())) {
636 Out << "(";
637 printType(I->getType());
638 Out << ")";
639 }
640
641 if (isa<PointerType>(I->getType())) Out << "(long long)";
642 writeOperand(I->getOperand(0));
643
644 switch (I->getOpcode()) {
645 case Instruction::Add: Out << " + "; break;
646 case Instruction::Sub: Out << " - "; break;
647 case Instruction::Mul: Out << "*"; break;
648 case Instruction::Div: Out << "/"; break;
649 case Instruction::Rem: Out << "%"; break;
650 case Instruction::And: Out << " & "; break;
651 case Instruction::Or: Out << " | "; break;
652 case Instruction::Xor: Out << " ^ "; break;
653 case Instruction::SetEQ: Out << " == "; break;
654 case Instruction::SetNE: Out << " != "; break;
655 case Instruction::SetLE: Out << " <= "; break;
656 case Instruction::SetGE: Out << " >= "; break;
657 case Instruction::SetLT: Out << " < "; break;
658 case Instruction::SetGT: Out << " > "; break;
659 case Instruction::Shl : Out << " << "; break;
660 case Instruction::Shr : Out << " >> "; break;
661 default: cerr << "Invalid operator type!" << I; abort();
662 }
663
664 if (isa<PointerType>(I->getType())) Out << "(long long)";
665 writeOperand(I->getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000666}
667
668void CWriter::visitCastInst(CastInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000669 Out << "(";
670 printType(I->getType());
671 Out << ")";
672 writeOperand(I->getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000673}
674
675void CWriter::visitCallInst(CallInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000676 const PointerType *PTy = cast<PointerType>(I->getCalledValue()->getType());
677 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
678 const Type *RetTy = FTy->getReturnType();
679
680 Out << getValueName(I->getOperand(0)) << "(";
681
682 if (I->getNumOperands() > 1) {
683 writeOperand(I->getOperand(1));
684
685 for (unsigned op = 2, Eop = I->getNumOperands(); op != Eop; ++op) {
686 Out << ", ";
687 writeOperand(I->getOperand(op));
688 }
689 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000690 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000691}
692
693void CWriter::visitMallocInst(MallocInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000694 Out << "(";
695 printType(I->getType());
696 Out << ")malloc(sizeof(";
697 printType(I->getType()->getElementType());
698 Out << ")";
699
700 if (I->isArrayAllocation()) {
701 Out << " * " ;
702 writeOperand(I->getOperand(0));
703 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000704 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000705}
706
707void CWriter::visitAllocaInst(AllocaInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000708 Out << "(";
709 printType(I->getType());
710 Out << ") alloca(sizeof(";
711 printType(I->getType()->getElementType());
712 Out << ")";
713 if (I->isArrayAllocation()) {
714 Out << " * " ;
715 writeOperand(I->getOperand(0));
716 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000717 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000718}
719
720void CWriter::visitFreeInst(FreeInst *I) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000721 Out << "free(";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000722 writeOperand(I->getOperand(0));
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000723 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000724}
725
726void CWriter::printIndexingExpr(MemAccessInst *MAI) {
727 MemAccessInst::op_iterator I = MAI->idx_begin(), E = MAI->idx_end();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000728 if (I == E) {
729 // If accessing a global value with no indexing, avoid *(&GV) syndrome
730 if (GlobalValue *V = dyn_cast<GlobalValue>(MAI->getPointerOperand())) {
731 writeOperandInternal(V);
732 return;
733 }
734
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000735 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000736 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000737
738 writeOperand(MAI->getPointerOperand());
739
740 if (I == E) return;
741
742 // Print out the -> operator if possible...
743 Constant *CI = dyn_cast<Constant>(*I);
744 if (CI && CI->isNullValue() && I+1 != E &&
745 (*(I+1))->getType() == Type::UByteTy) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000746 Out << "->field" << cast<ConstantUInt>(*(I+1))->getValue();
747 I += 2;
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000748 }
749
750 for (; I != E; ++I)
751 if ((*I)->getType() == Type::UIntTy) {
752 Out << "[";
753 writeOperand(*I);
754 Out << "]";
755 } else {
756 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
757 }
758}
759
760void CWriter::visitLoadInst(LoadInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000761 printIndexingExpr(I);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000762}
763
764void CWriter::visitStoreInst(StoreInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000765 printIndexingExpr(I);
766 Out << " = ";
767 writeOperand(I->getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000768}
769
770void CWriter::visitGetElementPtrInst(GetElementPtrInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000771 Out << "&";
772 printIndexingExpr(I);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000773}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000774
775//===----------------------------------------------------------------------===//
776// External Interface declaration
777//===----------------------------------------------------------------------===//
778
Chris Lattnerf34ee812002-05-09 03:12:34 +0000779void WriteToC(const Module *M, ostream &Out) {
780 assert(M && "You can't write a null module!!");
781 SlotCalculator SlotTable(M, false);
782 CWriter W(Out, SlotTable, M);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000783 W.write((Module*)M);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000784 Out.flush();
785}