blob: bdac6a101e7b0939ba50522637f50261d1b15e0d [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.
Chris Lattner594b9fa2002-05-21 21:10:04 +0000359 { // Scope to delete the FoundNames set when we are done with it...
Chris Lattner78771c82002-05-17 04:55:35 +0000360 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 Lattner594b9fa2002-05-21 21:10:04 +0000382 << "#include <malloc.h>\n"
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000383 << "#include <alloca.h>\n\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000384
385 // Provide a definition for null if one does not already exist.
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000386 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000387 << "typedef unsigned char bool;\n"
388
389 << "\n\n/* Global Symbols */\n";
390
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000391 // Loop over the symbol table, emitting all named constants...
392 if (M->hasSymbolTable())
393 printSymbolTable(*M->getSymbolTable());
394
Chris Lattner16c7bb22002-05-09 02:28:59 +0000395 Out << "\n\n/* Global Data */\n";
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000396 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
397 GlobalVariable *GV = *I;
398 if (GV->hasInternalLinkage()) Out << "static ";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000399 printType(GV->getType()->getElementType(), getValueName(GV));
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000400
401 if (GV->hasInitializer()) {
402 Out << " = " ;
403 writeOperand(GV->getInitializer());
404 }
405 Out << ";\n";
406 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000407
Chris Lattner16c7bb22002-05-09 02:28:59 +0000408 // First output all the declarations of the functions as C requires Functions
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000409 // be declared before they are used.
Chris Lattner16c7bb22002-05-09 02:28:59 +0000410 //
411 Out << "\n\n/* Function Declarations */\n";
412 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunctionDecl));
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000413
Chris Lattner16c7bb22002-05-09 02:28:59 +0000414 // Output all of the functions...
415 Out << "\n\n/* Function Bodies */\n";
416 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunction));
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000417}
418
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000419
420// printSymbolTable - Run through symbol table looking for named constants
421// if a named constant is found, emit it's declaration...
422// Assuming that symbol table has only types and constants.
423void CWriter::printSymbolTable(const SymbolTable &ST) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000424 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
425 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
426 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
427
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000428 for (; I != End; ++I)
429 if (const Type *Ty = dyn_cast<const StructType>(I->second)) {
430 string Name = "struct l_" + I->first;
431 Out << Name << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000432
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000433 TypeNames.insert(std::make_pair(Ty, Name));
434 }
435 }
436
437 Out << "\n";
438
439 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
440 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
441 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
442
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000443 for (; I != End; ++I) {
444 const Value *V = I->second;
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000445 if (const Type *Ty = dyn_cast<const Type>(V)) {
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000446 string Name = "l_" + I->first;
Chris Lattner1f02c892002-05-09 20:14:10 +0000447 if (isa<StructType>(Ty))
448 Name = "struct " + Name;
449 else
450 Out << "typedef ";
451
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000452 Out << calcTypeNameVar(Ty, TypeNames, Name, true) << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000453 }
454 }
455 }
456}
457
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000458
Chris Lattner16c7bb22002-05-09 02:28:59 +0000459// printFunctionDecl - Print function declaration
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000460//
Chris Lattner16c7bb22002-05-09 02:28:59 +0000461void CWriter::printFunctionDecl(const Function *F) {
462 printFunctionSignature(F);
463 Out << ";\n";
464}
465
466void CWriter::printFunctionSignature(const Function *F) {
467 if (F->hasInternalLinkage()) Out << "static ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000468
469 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +0000470 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000471
Chris Lattner16c7bb22002-05-09 02:28:59 +0000472 // Print out the return type and name...
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000473 printType(F->getReturnType());
Chris Lattner1f02c892002-05-09 20:14:10 +0000474 Out << getValueName(F) << "(";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000475
Chris Lattner16c7bb22002-05-09 02:28:59 +0000476 if (!F->isExternal()) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000477 if (!F->getArgumentList().empty()) {
Chris Lattner3af3ba82002-05-09 21:31:18 +0000478 printType(F->getArgumentList().front()->getType(),
479 getValueName(F->getArgumentList().front()));
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000480
481 for (Function::ArgumentListType::const_iterator
482 I = F->getArgumentList().begin()+1,
483 E = F->getArgumentList().end(); I != E; ++I) {
484 Out << ", ";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000485 printType((*I)->getType(), getValueName(*I));
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000486 }
487 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000488 } else {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000489 // Loop over the arguments, printing them...
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000490 for (FunctionType::ParamTypes::const_iterator I =
Chris Lattner16c7bb22002-05-09 02:28:59 +0000491 FT->getParamTypes().begin(),
492 E = FT->getParamTypes().end(); I != E; ++I) {
493 if (I != FT->getParamTypes().begin()) Out << ", ";
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000494 printType(*I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000495 }
496 }
497
498 // Finish printing arguments...
Chris Lattner16c7bb22002-05-09 02:28:59 +0000499 if (FT->isVarArg()) {
500 if (FT->getParamTypes().size()) Out << ", ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000501 Out << "..."; // Output varargs portion of signature!
502 }
Chris Lattner16c7bb22002-05-09 02:28:59 +0000503 Out << ")";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000504}
505
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000506
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000507void CWriter::printFunction(Function *F) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000508 if (F->isExternal()) return;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000509
Chris Lattnerf34ee812002-05-09 03:12:34 +0000510 Table.incorporateFunction(F);
511
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000512 printFunctionSignature(F);
513 Out << " {\n";
514
Chris Lattner497e19a2002-05-09 20:39:03 +0000515 // print local variable information for the function
Chris Lattner7683a122002-05-09 20:33:35 +0000516 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000517 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000518 Out << " ";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000519 printType((*I)->getType(), getValueName(*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000520 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000521 }
Chris Lattner16c7bb22002-05-09 02:28:59 +0000522
523 // print the basic blocks
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000524 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
525 BasicBlock *BB = *I, *Prev = I != F->begin() ? *(I-1) : 0;
526
527 // Don't print the label for the basic block if there are no uses, or if the
528 // only terminator use is the precessor basic block's terminator. We have
529 // to scan the use list because PHI nodes use basic blocks too but do not
530 // require a label to be generated.
531 //
532 bool NeedsLabel = false;
533 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
534 UI != UE; ++UI)
535 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
536 if (TI != Prev->getTerminator()) {
537 NeedsLabel = true;
538 break;
539 }
540
541 if (NeedsLabel) Out << getValueName(BB) << ":\n";
542
543 // Output all of the instructions in the basic block...
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000544 for (BasicBlock::iterator II = BB->begin(), E = BB->end()-1;
545 II != E; ++II) {
546 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
547 Instruction *I = *II;
548 if (I->getType() != Type::VoidTy)
549 outputLValue(I);
550 else
551 Out << " ";
552 visit(I);
553 Out << ";\n";
554 }
555 }
556
557 // Don't emit prefix or suffix for the terminator...
558 visit(BB->getTerminator());
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000559 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000560
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000561 Out << "}\n\n";
Chris Lattnerf34ee812002-05-09 03:12:34 +0000562 Table.purgeFunction();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000563}
564
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000565// Specific Instruction type classes... note that all of the casts are
566// neccesary because we use the instruction classes as opaque types...
567//
568void CWriter::visitReturnInst(ReturnInst *I) {
569 // Don't output a void return if this is the last basic block in the function
570 if (I->getNumOperands() == 0 &&
Chris Lattner963b70b2002-05-21 18:05:19 +0000571 *(I->getParent()->getParent()->end()-1) == I->getParent() &&
572 !I->getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000573 return;
Chris Lattner963b70b2002-05-21 18:05:19 +0000574 }
Chris Lattner44408262002-05-09 03:50:42 +0000575
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000576 Out << " return";
577 if (I->getNumOperands()) {
578 Out << " ";
579 writeOperand(I->getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000580 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000581 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000582}
583
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000584// Return true if BB1 immediately preceeds BB2.
585static bool BBFollowsBB(BasicBlock *BB1, BasicBlock *BB2) {
586 Function *F = BB1->getParent();
587 Function::iterator I = find(F->begin(), F->end(), BB1);
588 assert(I != F->end() && "BB not in function!");
589 return *(I+1) == BB2;
590}
591
592static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
593 // If PHI nodes need copies, we need the copy code...
594 if (isa<PHINode>(To->front()) ||
595 !BBFollowsBB(From, To)) // Not directly successor, need goto
596 return true;
597
598 // Otherwise we don't need the code.
599 return false;
600}
601
602void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
603 unsigned Indent) {
604 for (BasicBlock::iterator I = Succ->begin();
605 PHINode *PN = dyn_cast<PHINode>(*I); ++I) {
606 // now we have to do the printing
607 Out << string(Indent, ' ');
608 outputLValue(PN);
609 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
610 Out << "; /* for PHI node */\n";
611 }
612
613 if (!BBFollowsBB(CurBB, Succ)) {
614 Out << string(Indent, ' ') << " goto ";
615 writeOperand(Succ);
616 Out << ";\n";
617 }
618}
619
620// Brach instruction printing - Avoid printing out a brach to a basic block that
621// immediately succeeds the current one.
622//
623void CWriter::visitBranchInst(BranchInst *I) {
624 if (I->isConditional()) {
625 if (isGotoCodeNeccessary(I->getParent(), I->getSuccessor(0))) {
626 Out << " if (";
627 writeOperand(I->getCondition());
628 Out << ") {\n";
629
630 printBranchToBlock(I->getParent(), I->getSuccessor(0), 2);
631
632 if (isGotoCodeNeccessary(I->getParent(), I->getSuccessor(1))) {
633 Out << " } else {\n";
634 printBranchToBlock(I->getParent(), I->getSuccessor(1), 2);
635 }
636 } else {
637 // First goto not neccesary, assume second one is...
638 Out << " if (!";
639 writeOperand(I->getCondition());
640 Out << ") {\n";
641
642 printBranchToBlock(I->getParent(), I->getSuccessor(1), 2);
643 }
644
645 Out << " }\n";
646 } else {
647 printBranchToBlock(I->getParent(), I->getSuccessor(0), 0);
648 }
649 Out << "\n";
650}
651
652
653void CWriter::visitNot(GenericUnaryInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000654 Out << "~";
655 writeOperand(I->getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000656}
657
658void CWriter::visitBinaryOperator(Instruction *I) {
659 // binary instructions, shift instructions, setCond instructions.
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000660 if (isa<PointerType>(I->getType())) {
661 Out << "(";
662 printType(I->getType());
663 Out << ")";
664 }
665
666 if (isa<PointerType>(I->getType())) Out << "(long long)";
667 writeOperand(I->getOperand(0));
668
669 switch (I->getOpcode()) {
670 case Instruction::Add: Out << " + "; break;
671 case Instruction::Sub: Out << " - "; break;
672 case Instruction::Mul: Out << "*"; break;
673 case Instruction::Div: Out << "/"; break;
674 case Instruction::Rem: Out << "%"; break;
675 case Instruction::And: Out << " & "; break;
676 case Instruction::Or: Out << " | "; break;
677 case Instruction::Xor: Out << " ^ "; break;
678 case Instruction::SetEQ: Out << " == "; break;
679 case Instruction::SetNE: Out << " != "; break;
680 case Instruction::SetLE: Out << " <= "; break;
681 case Instruction::SetGE: Out << " >= "; break;
682 case Instruction::SetLT: Out << " < "; break;
683 case Instruction::SetGT: Out << " > "; break;
684 case Instruction::Shl : Out << " << "; break;
685 case Instruction::Shr : Out << " >> "; break;
686 default: cerr << "Invalid operator type!" << I; abort();
687 }
688
689 if (isa<PointerType>(I->getType())) Out << "(long long)";
690 writeOperand(I->getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000691}
692
693void CWriter::visitCastInst(CastInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000694 Out << "(";
695 printType(I->getType());
696 Out << ")";
697 writeOperand(I->getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000698}
699
700void CWriter::visitCallInst(CallInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000701 const PointerType *PTy = cast<PointerType>(I->getCalledValue()->getType());
702 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
703 const Type *RetTy = FTy->getReturnType();
704
705 Out << getValueName(I->getOperand(0)) << "(";
706
707 if (I->getNumOperands() > 1) {
708 writeOperand(I->getOperand(1));
709
710 for (unsigned op = 2, Eop = I->getNumOperands(); op != Eop; ++op) {
711 Out << ", ";
712 writeOperand(I->getOperand(op));
713 }
714 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000715 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000716}
717
718void CWriter::visitMallocInst(MallocInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000719 Out << "(";
720 printType(I->getType());
721 Out << ")malloc(sizeof(";
722 printType(I->getType()->getElementType());
723 Out << ")";
724
725 if (I->isArrayAllocation()) {
726 Out << " * " ;
727 writeOperand(I->getOperand(0));
728 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000729 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000730}
731
732void CWriter::visitAllocaInst(AllocaInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000733 Out << "(";
734 printType(I->getType());
735 Out << ") alloca(sizeof(";
736 printType(I->getType()->getElementType());
737 Out << ")";
738 if (I->isArrayAllocation()) {
739 Out << " * " ;
740 writeOperand(I->getOperand(0));
741 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000742 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000743}
744
745void CWriter::visitFreeInst(FreeInst *I) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000746 Out << "free(";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000747 writeOperand(I->getOperand(0));
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000748 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000749}
750
751void CWriter::printIndexingExpr(MemAccessInst *MAI) {
752 MemAccessInst::op_iterator I = MAI->idx_begin(), E = MAI->idx_end();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000753 if (I == E) {
754 // If accessing a global value with no indexing, avoid *(&GV) syndrome
755 if (GlobalValue *V = dyn_cast<GlobalValue>(MAI->getPointerOperand())) {
756 writeOperandInternal(V);
757 return;
758 }
759
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000760 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000761 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000762
763 writeOperand(MAI->getPointerOperand());
764
765 if (I == E) return;
766
767 // Print out the -> operator if possible...
768 Constant *CI = dyn_cast<Constant>(*I);
769 if (CI && CI->isNullValue() && I+1 != E &&
770 (*(I+1))->getType() == Type::UByteTy) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000771 Out << "->field" << cast<ConstantUInt>(*(I+1))->getValue();
772 I += 2;
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000773 }
774
775 for (; I != E; ++I)
776 if ((*I)->getType() == Type::UIntTy) {
777 Out << "[";
778 writeOperand(*I);
779 Out << "]";
780 } else {
781 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
782 }
783}
784
785void CWriter::visitLoadInst(LoadInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000786 printIndexingExpr(I);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000787}
788
789void CWriter::visitStoreInst(StoreInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000790 printIndexingExpr(I);
791 Out << " = ";
792 writeOperand(I->getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000793}
794
795void CWriter::visitGetElementPtrInst(GetElementPtrInst *I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000796 Out << "&";
797 printIndexingExpr(I);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000798}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000799
800//===----------------------------------------------------------------------===//
801// External Interface declaration
802//===----------------------------------------------------------------------===//
803
Chris Lattnerf34ee812002-05-09 03:12:34 +0000804void WriteToC(const Module *M, ostream &Out) {
805 assert(M && "You can't write a null module!!");
806 SlotCalculator SlotTable(M, false);
807 CWriter W(Out, SlotTable, M);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000808 W.write((Module*)M);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000809 Out.flush();
810}