blob: f318764b026919529e72a2087e5b23632a4d85ea [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//
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00003// This library converts LLVM code to C code, compilable by GCC.
Chris Lattner16c7bb22002-05-09 02:28:59 +00004//
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00005//===-----------------------------------------------------------------------==//
6#include "llvm/Assembly/CWriter.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00007#include "llvm/Constants.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +00008#include "llvm/DerivedTypes.h"
9#include "llvm/Module.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000010#include "llvm/iMemory.h"
11#include "llvm/iTerminators.h"
12#include "llvm/iPHINode.h"
13#include "llvm/iOther.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000014#include "llvm/iOperators.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000015#include "llvm/Pass.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000016#include "llvm/SymbolTable.h"
Chris Lattner3af3ba82002-05-09 21:31:18 +000017#include "llvm/SlotCalculator.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000018#include "llvm/Analysis/FindUsedTypes.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000019#include "llvm/Analysis/ConstantsScanner.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000020#include "llvm/Support/InstVisitor.h"
Chris Lattner7683a122002-05-09 20:33:35 +000021#include "llvm/Support/InstIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000022#include "Support/StringExtras.h"
23#include "Support/STLExtras.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000024#include <algorithm>
Chris Lattner78771c82002-05-17 04:55:35 +000025#include <set>
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000026using std::string;
27using std::map;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000028using std::ostream;
29
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +000030
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000031namespace {
Chris Lattner0e9f93e2002-08-31 00:29:16 +000032 class CWriter : public Pass, public InstVisitor<CWriter> {
33 ostream &Out;
34 SlotCalculator *Table;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000035 const Module *TheModule;
36 map<const Type *, string> TypeNames;
Chris Lattner78771c82002-05-17 04:55:35 +000037 std::set<const Value*> MangledGlobals;
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +000038 bool needsMalloc;
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +000039
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000040 map<const ConstantFP *, unsigned> FPConstantMap;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000041 public:
Chris Lattner0e9f93e2002-08-31 00:29:16 +000042 CWriter(ostream &o) : Out(o) {}
43
44 void getAnalysisUsage(AnalysisUsage &AU) const {
45 AU.setPreservesAll();
46 AU.addRequired<FindUsedTypes>();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000047 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +000048
49 virtual bool run(Module &M) {
50 // Initialize
51 Table = new SlotCalculator(&M, false);
52 TheModule = &M;
53
54 // Ensure that all structure types have names...
55 bool Changed = nameAllUsedStructureTypes(M);
56
57 // Run...
58 printModule(&M);
59
60 // Free memory...
61 delete Table;
62 TypeNames.clear();
63 MangledGlobals.clear();
64 return false;
65 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000066
Chris Lattner83c57752002-08-19 22:17:53 +000067 ostream &printType(const Type *Ty, const string &VariableName = "",
Vikram S. Adve969c4ad2002-08-25 20:00:08 +000068 bool IgnoreName = false, bool namedContext = true);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000069
Chris Lattnerbb03efd2002-06-25 15:57:03 +000070 void writeOperand(Value *Operand);
71 void writeOperandInternal(Value *Operand);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000072
73 string getValueName(const Value *V);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000074
Chris Lattner4fbf26d2002-05-09 20:53:56 +000075 private :
Chris Lattner0e9f93e2002-08-31 00:29:16 +000076 bool nameAllUsedStructureTypes(Module &M);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +000077 void printModule(Module *M);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000078 void printSymbolTable(const SymbolTable &ST);
Chris Lattner2c601a72002-09-20 15:05:40 +000079 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000080 void printGlobal(const GlobalVariable *GV);
Chris Lattner4cda8352002-08-20 16:55:48 +000081 void printFunctionSignature(const Function *F, bool Prototype);
82
Chris Lattner8c3c4bf2002-05-09 15:49:41 +000083 void printFunction(Function *);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000084
Chris Lattner6d492922002-08-19 21:32:41 +000085 void printConstant(Constant *CPV);
86 void printConstantArray(ConstantArray *CPA);
87
Chris Lattnerd0c668c2002-05-09 21:18:38 +000088 // isInlinableInst - Attempt to inline instructions into their uses to build
89 // trees as much as possible. To do this, we have to consistently decide
90 // what is acceptable to inline, so that variable declarations don't get
91 // printed and an extra copy of the expr is not emitted.
92 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +000093 static bool isInlinableInst(const Instruction &I) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +000094 // Must be an expression, must be used exactly once. If it is dead, we
95 // emit it inline where it would go.
Chris Lattnerbb03efd2002-06-25 15:57:03 +000096 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
Nick Hildenbrandt2cf2cbc2002-11-06 20:07:54 +000097 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
98 isa<LoadInst>(I)) // Don't inline a load across a store!
Chris Lattnerd0c668c2002-05-09 21:18:38 +000099 return false;
100
101 // Only inline instruction it it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000102 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000103 }
104
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000105 // Instruction visitation functions
106 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000107
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000108 void visitReturnInst(ReturnInst &I);
109 void visitBranchInst(BranchInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000110
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000111 void visitPHINode(PHINode &I) {}
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000112 void visitBinaryOperator(Instruction &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000113
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000114 void visitCastInst (CastInst &I);
115 void visitCallInst (CallInst &I);
116 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000117
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000118 void visitMallocInst(MallocInst &I);
119 void visitAllocaInst(AllocaInst &I);
120 void visitFreeInst (FreeInst &I);
121 void visitLoadInst (LoadInst &I);
122 void visitStoreInst (StoreInst &I);
123 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000124
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000125 void visitInstruction(Instruction &I) {
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000126 std::cerr << "C Writer does not know about " << I;
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000127 abort();
128 }
129
130 void outputLValue(Instruction *I) {
131 Out << " " << getValueName(I) << " = ";
132 }
133 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
134 unsigned Indent);
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000135 void printIndexingExpression(Value *Ptr, User::op_iterator I,
136 User::op_iterator E);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000137 };
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000138}
139
Chris Lattner2f499022002-05-09 04:21:21 +0000140// We dont want identifier names with ., space, - in them.
141// So we replace them with _
142static string makeNameProper(string x) {
143 string tmp;
144 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
145 switch (*sI) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000146 case '.': tmp += "d_"; break;
147 case ' ': tmp += "s_"; break;
148 case '-': tmp += "D_"; break;
Chris Lattner2f499022002-05-09 04:21:21 +0000149 default: tmp += *sI;
150 }
151
152 return tmp;
153}
154
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000155string CWriter::getValueName(const Value *V) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000156 if (V->hasName()) { // Print out the label if it exists...
157 if (isa<GlobalValue>(V) && // Do not mangle globals...
158 cast<GlobalValue>(V)->hasExternalLinkage() && // Unless it's internal or
159 !MangledGlobals.count(V)) // Unless the name would collide if we don't
Chris Lattner2f499022002-05-09 04:21:21 +0000160 return makeNameProper(V->getName());
161
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000162 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
163 makeNameProper(V->getName());
Chris Lattner2f499022002-05-09 04:21:21 +0000164 }
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000165
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000166 int Slot = Table->getValSlot(V);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000167 assert(Slot >= 0 && "Invalid value!");
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000168 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000169}
170
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000171// A pointer type should not use parens around *'s alone, e.g., (**)
172inline bool ptrTypeNameNeedsParens(const string &NameSoFar) {
173 return (NameSoFar.find_last_not_of('*') != std::string::npos);
174}
175
Chris Lattner83c57752002-08-19 22:17:53 +0000176// Pass the Type* and the variable name and this prints out the variable
177// declaration.
178//
179ostream &CWriter::printType(const Type *Ty, const string &NameSoFar,
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000180 bool IgnoreName, bool namedContext) {
Chris Lattner83c57752002-08-19 22:17:53 +0000181 if (Ty->isPrimitiveType())
182 switch (Ty->getPrimitiveID()) {
183 case Type::VoidTyID: return Out << "void " << NameSoFar;
184 case Type::BoolTyID: return Out << "bool " << NameSoFar;
185 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
186 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
187 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
188 case Type::ShortTyID: return Out << "short " << NameSoFar;
189 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
190 case Type::IntTyID: return Out << "int " << NameSoFar;
191 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
192 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
193 case Type::FloatTyID: return Out << "float " << NameSoFar;
194 case Type::DoubleTyID: return Out << "double " << NameSoFar;
195 default :
196 std::cerr << "Unknown primitive type: " << Ty << "\n";
197 abort();
198 }
199
200 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000201 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattner83c57752002-08-19 22:17:53 +0000202 map<const Type *, string>::iterator I = TypeNames.find(Ty);
203 if (I != TypeNames.end()) {
204 return Out << I->second << " " << NameSoFar;
205 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000206 }
Chris Lattner83c57752002-08-19 22:17:53 +0000207
Chris Lattner83c57752002-08-19 22:17:53 +0000208 switch (Ty->getPrimitiveID()) {
209 case Type::FunctionTyID: {
210 const FunctionType *MTy = cast<FunctionType>(Ty);
211 printType(MTy->getReturnType(), "");
Nick Hildenbrandt7e9fea72002-11-01 17:37:09 +0000212 Out << " (" << NameSoFar << ") (";
Chris Lattner83c57752002-08-19 22:17:53 +0000213
214 for (FunctionType::ParamTypes::const_iterator
215 I = MTy->getParamTypes().begin(),
216 E = MTy->getParamTypes().end(); I != E; ++I) {
217 if (I != MTy->getParamTypes().begin())
218 Out << ", ";
219 printType(*I, "");
220 }
221 if (MTy->isVarArg()) {
222 if (!MTy->getParamTypes().empty())
223 Out << ", ";
224 Out << "...";
225 }
226 return Out << ")";
227 }
228 case Type::StructTyID: {
229 const StructType *STy = cast<StructType>(Ty);
230 Out << NameSoFar + " {\n";
231 unsigned Idx = 0;
232 for (StructType::ElementTypes::const_iterator
233 I = STy->getElementTypes().begin(),
234 E = STy->getElementTypes().end(); I != E; ++I) {
235 Out << " ";
236 printType(*I, "field" + utostr(Idx++));
237 Out << ";\n";
238 }
239 return Out << "}";
240 }
241
242 case Type::PointerTyID: {
243 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000244 std::string ptrName = "*" + NameSoFar;
245
246 // Do not need parens around "* NameSoFar" if NameSoFar consists only
247 // of zero or more '*' chars *and* this is not an unnamed pointer type
248 // such as the result type in a cast statement. Otherwise, enclose in ( ).
Nick Hildenbrandtc14ded42002-09-23 21:02:50 +0000249 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
250 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000251 ptrName = "(" + ptrName + ")"; //
252
Vikram S. Adve42eb2ba2002-08-24 14:44:23 +0000253 return printType(PTy->getElementType(), ptrName);
Chris Lattner83c57752002-08-19 22:17:53 +0000254 }
255
256 case Type::ArrayTyID: {
257 const ArrayType *ATy = cast<ArrayType>(Ty);
258 unsigned NumElements = ATy->getNumElements();
259 return printType(ATy->getElementType(),
260 NameSoFar + "[" + utostr(NumElements) + "]");
261 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000262
263 case Type::OpaqueTyID: {
264 static int Count = 0;
265 string TyName = "struct opaque_" + itostr(Count++);
266 assert(TypeNames.find(Ty) == TypeNames.end());
267 TypeNames[Ty] = TyName;
268 return Out << TyName << " " << NameSoFar;
269 }
Chris Lattner83c57752002-08-19 22:17:53 +0000270 default:
271 assert(0 && "Unhandled case in getTypeProps!");
272 abort();
273 }
274
275 return Out;
276}
277
Chris Lattner6d492922002-08-19 21:32:41 +0000278void CWriter::printConstantArray(ConstantArray *CPA) {
279
280 // As a special case, print the array as a string if it is an array of
281 // ubytes or an array of sbytes with positive values.
282 //
283 const Type *ETy = CPA->getType()->getElementType();
284 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
285
286 // Make sure the last character is a null char, as automatically added by C
287 if (CPA->getNumOperands() == 0 ||
288 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
289 isString = false;
290
291 if (isString) {
292 Out << "\"";
293 // Do not include the last character, which we know is null
294 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
295 unsigned char C = (ETy == Type::SByteTy) ?
296 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
297 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
298
299 if (isprint(C)) {
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000300 if (C == '"' || C == '\\')
301 Out << "\\" << C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000302 else
303 Out << C;
Chris Lattner6d492922002-08-19 21:32:41 +0000304 } else {
305 switch (C) {
306 case '\n': Out << "\\n"; break;
307 case '\t': Out << "\\t"; break;
308 case '\r': Out << "\\r"; break;
309 case '\v': Out << "\\v"; break;
310 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000311 case '\"': Out << "\\\""; break;
312 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000313 default:
314 Out << "\\x";
315 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
316 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
317 break;
318 }
319 }
320 }
321 Out << "\"";
322 } else {
323 Out << "{";
324 if (CPA->getNumOperands()) {
325 Out << " ";
326 printConstant(cast<Constant>(CPA->getOperand(0)));
327 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
328 Out << ", ";
329 printConstant(cast<Constant>(CPA->getOperand(i)));
330 }
331 }
332 Out << " }";
333 }
334}
335
336
337// printConstant - The LLVM Constant to C Constant converter.
338void CWriter::printConstant(Constant *CPV) {
339 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
340 switch (CE->getOpcode()) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000341 case Instruction::Cast:
342 Out << "((";
343 printType(CPV->getType());
344 Out << ")";
345 printConstant(cast<Constant>(CPV->getOperand(0)));
346 Out << ")";
347 return;
348
349 case Instruction::GetElementPtr:
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000350 Out << "(&(";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000351 printIndexingExpression(CPV->getOperand(0),
352 CPV->op_begin()+1, CPV->op_end());
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000353 Out << "))";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000354 return;
355 case Instruction::Add:
356 Out << "(";
357 printConstant(cast<Constant>(CPV->getOperand(0)));
358 Out << " + ";
359 printConstant(cast<Constant>(CPV->getOperand(1)));
360 Out << ")";
361 return;
362 case Instruction::Sub:
363 Out << "(";
364 printConstant(cast<Constant>(CPV->getOperand(0)));
365 Out << " - ";
366 printConstant(cast<Constant>(CPV->getOperand(1)));
367 Out << ")";
368 return;
369
Chris Lattner6d492922002-08-19 21:32:41 +0000370 default:
371 std::cerr << "CWriter Error: Unhandled constant expression: "
372 << CE << "\n";
373 abort();
374 }
375 }
376
377 switch (CPV->getType()->getPrimitiveID()) {
378 case Type::BoolTyID:
379 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
380 case Type::SByteTyID:
381 case Type::ShortTyID:
382 case Type::IntTyID:
383 Out << cast<ConstantSInt>(CPV)->getValue(); break;
384 case Type::LongTyID:
385 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
386
387 case Type::UByteTyID:
388 case Type::UShortTyID:
389 Out << cast<ConstantUInt>(CPV)->getValue(); break;
390 case Type::UIntTyID:
391 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
392 case Type::ULongTyID:
393 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
394
395 case Type::FloatTyID:
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000396 case Type::DoubleTyID: {
397 ConstantFP *FPC = cast<ConstantFP>(CPV);
398 map<const ConstantFP *, unsigned>::iterator I = FPConstantMap.find(FPC);
399 if (I != FPConstantMap.end()) {
400 // Because of FP precision problems we must load from a stack allocated
401 // value that holds the value in hex.
402 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
403 << "*)&FloatConstant" << I->second << ")";
404 } else {
405 Out << FPC->getValue();
406 }
407 break;
408 }
Chris Lattner6d492922002-08-19 21:32:41 +0000409
410 case Type::ArrayTyID:
411 printConstantArray(cast<ConstantArray>(CPV));
412 break;
413
414 case Type::StructTyID: {
415 Out << "{";
416 if (CPV->getNumOperands()) {
417 Out << " ";
418 printConstant(cast<Constant>(CPV->getOperand(0)));
419 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
420 Out << ", ";
421 printConstant(cast<Constant>(CPV->getOperand(i)));
422 }
423 }
424 Out << " }";
425 break;
426 }
427
428 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000429 if (isa<ConstantPointerNull>(CPV)) {
Nick Hildenbrandtf0fca362002-10-28 19:54:06 +0000430 Out << "(NULL)";
Chris Lattner6d492922002-08-19 21:32:41 +0000431 break;
432 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
433 writeOperand(CPR->getValue());
434 break;
435 }
436 // FALL THROUGH
437 default:
438 std::cerr << "Unknown constant type: " << CPV << "\n";
439 abort();
440 }
441}
442
443void CWriter::writeOperandInternal(Value *Operand) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000444 if (Instruction *I = dyn_cast<Instruction>(Operand))
445 if (isInlinableInst(*I)) {
446 // Should we inline this instruction to build a tree?
447 Out << "(";
448 visit(*I);
449 Out << ")";
450 return;
451 }
452
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +0000453 if (Operand->hasName()) {
Chris Lattner6d492922002-08-19 21:32:41 +0000454 Out << getValueName(Operand);
455 } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
456 printConstant(CPV);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000457 } else {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000458 int Slot = Table->getValSlot(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000459 assert(Slot >= 0 && "Malformed LLVM!");
460 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
461 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000462}
463
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000464void CWriter::writeOperand(Value *Operand) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000465 if (isa<GlobalVariable>(Operand))
466 Out << "(&"; // Global variables are references as their addresses by llvm
467
468 writeOperandInternal(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000469
470 if (isa<GlobalVariable>(Operand))
471 Out << ")";
472}
473
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000474// nameAllUsedStructureTypes - If there are structure types in the module that
475// are used but do not have names assigned to them in the symbol table yet then
476// we assign them names now.
477//
478bool CWriter::nameAllUsedStructureTypes(Module &M) {
479 // Get a set of types that are used by the program...
480 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
481
482 // Loop over the module symbol table, removing types from UT that are already
483 // named.
484 //
485 SymbolTable *MST = M.getSymbolTableSure();
486 if (MST->find(Type::TypeTy) != MST->end())
487 for (SymbolTable::type_iterator I = MST->type_begin(Type::TypeTy),
488 E = MST->type_end(Type::TypeTy); I != E; ++I)
489 UT.erase(cast<Type>(I->second));
490
491 // UT now contains types that are not named. Loop over it, naming structure
492 // types.
493 //
494 bool Changed = false;
495 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
496 I != E; ++I)
497 if (const StructType *ST = dyn_cast<StructType>(*I)) {
498 ((Value*)ST)->setName("unnamed", MST);
499 Changed = true;
500 }
501 return Changed;
502}
503
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000504void CWriter::printModule(Module *M) {
Chris Lattner78771c82002-05-17 04:55:35 +0000505 // Calculate which global values have names that will collide when we throw
506 // away type information.
Chris Lattner594b9fa2002-05-21 21:10:04 +0000507 { // Scope to delete the FoundNames set when we are done with it...
Chris Lattner78771c82002-05-17 04:55:35 +0000508 std::set<string> FoundNames;
509 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000510 if (I->hasName()) // If the global has a name...
511 if (FoundNames.count(I->getName())) // And the name is already used
512 MangledGlobals.insert(I); // Mangle the name
Chris Lattner78771c82002-05-17 04:55:35 +0000513 else
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000514 FoundNames.insert(I->getName()); // Otherwise, keep track of name
Chris Lattner78771c82002-05-17 04:55:35 +0000515
516 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000517 if (I->hasName()) // If the global has a name...
518 if (FoundNames.count(I->getName())) // And the name is already used
519 MangledGlobals.insert(I); // Mangle the name
Chris Lattner78771c82002-05-17 04:55:35 +0000520 else
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000521 FoundNames.insert(I->getName()); // Otherwise, keep track of name
Chris Lattner78771c82002-05-17 04:55:35 +0000522 }
523
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000524 // printing stdlib inclusion
Nick Hildenbrandt98360a12002-10-11 21:40:44 +0000525 //Out << "#include <stdlib.h>\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000526
Chris Lattner16c7bb22002-05-09 02:28:59 +0000527 // get declaration for alloca
528 Out << "/* Provide Declarations */\n"
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000529 << "#include <alloca.h>\n\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000530
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000531 // Provide a definition for null if one does not already exist,
532 // and for `bool' if not compiling with a C++ compiler.
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000533 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000534 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000535
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000536 << "\n\n/* Support for floating point constants */\n"
537 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000538 << "typedef unsigned int ConstantFloatTy;\n"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000539
Chris Lattnera4d4a852002-08-19 21:48:40 +0000540 << "\n\n/* Global Declarations */\n";
541
542 // First output all the declarations for the program, because C requires
543 // Functions & globals to be declared before they are used.
544 //
Chris Lattner16c7bb22002-05-09 02:28:59 +0000545
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000546 // Loop over the symbol table, emitting all named constants...
547 if (M->hasSymbolTable())
548 printSymbolTable(*M->getSymbolTable());
549
Chris Lattnera4d4a852002-08-19 21:48:40 +0000550 // Global variable declarations...
551 if (!M->gempty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000552 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +0000553 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000554 if (I->hasExternalLinkage()) {
555 Out << "extern ";
556 printType(I->getType()->getElementType(), getValueName(I));
557 Out << ";\n";
558 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000559 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000560 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000561
Chris Lattnera4d4a852002-08-19 21:48:40 +0000562 // Function declarations
563 if (!M->empty()) {
564 Out << "\n/* Function Declarations */\n";
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000565 needsMalloc = true;
Chris Lattner4cda8352002-08-20 16:55:48 +0000566 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
567 printFunctionSignature(I, true);
568 Out << ";\n";
569 }
Chris Lattnera4d4a852002-08-19 21:48:40 +0000570 }
571
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000572 // Print Malloc prototype if needed
573 if (needsMalloc){
574 Out << "\n/* Malloc to make sun happy */\n";
575 Out << "extern void * malloc(size_t);\n\n";
576 }
577
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +0000578 // Output the global variable declerations
579 if (!M->gempty()) {
580 Out << "\n\n/* Global Variable Declerations */\n";
581 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
582 if (!I->isExternal()) {
583 Out << "extern ";
584 printType(I->getType()->getElementType(), getValueName(I));
585
586 Out << ";\n";
587 }
588 }
589
590
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000591 // Output the global variable definitions and contents...
Chris Lattnera4d4a852002-08-19 21:48:40 +0000592 if (!M->gempty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000593 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Chris Lattnere8e035b2002-10-16 20:08:47 +0000594 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
595 if (!I->isExternal()) {
596 if (I->hasInternalLinkage())
597 Out << "static ";
598 printType(I->getType()->getElementType(), getValueName(I));
Chris Lattnera4d4a852002-08-19 21:48:40 +0000599
Chris Lattnera4d4a852002-08-19 21:48:40 +0000600 Out << " = " ;
601 writeOperand(I->getInitializer());
Chris Lattnere8e035b2002-10-16 20:08:47 +0000602 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +0000603 }
Chris Lattnera4d4a852002-08-19 21:48:40 +0000604 }
605
Chris Lattner16c7bb22002-05-09 02:28:59 +0000606 // Output all of the functions...
Chris Lattnera4d4a852002-08-19 21:48:40 +0000607 if (!M->empty()) {
608 Out << "\n\n/* Function Bodies */\n";
609 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
610 printFunction(I);
611 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000612}
613
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000614
Chris Lattner2db41cd2002-09-20 15:12:13 +0000615/// printSymbolTable - Run through symbol table looking for type names. If a
616/// type name is found, emit it's declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +0000617///
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000618void CWriter::printSymbolTable(const SymbolTable &ST) {
Chris Lattner2db41cd2002-09-20 15:12:13 +0000619 // If there are no type names, exit early.
620 if (ST.find(Type::TypeTy) == ST.end())
621 return;
622
623 // We are only interested in the type plane of the symbol table...
624 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
625 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
626
Chris Lattner58d04d42002-09-20 15:18:30 +0000627 // Print out forward declarations for structure types before anything else!
628 Out << "/* Structure forward decls */\n";
629 for (; I != End; ++I)
630 if (const Type *STy = dyn_cast<StructType>(I->second)) {
631 string Name = "struct l_" + makeNameProper(I->first);
632 Out << Name << ";\n";
633 TypeNames.insert(std::make_pair(STy, Name));
634 }
635
636 Out << "\n";
637
638 // Now we can print out typedefs...
639 Out << "/* Typedefs */\n";
640 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
641 const Type *Ty = cast<Type>(I->second);
642 string Name = "l_" + makeNameProper(I->first);
643 Out << "typedef ";
Chris Lattner270d78a2002-09-20 15:20:24 +0000644 printType(Ty, Name);
Chris Lattner58d04d42002-09-20 15:18:30 +0000645 Out << ";\n";
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000646 }
647
648 Out << "\n";
649
Chris Lattner2c601a72002-09-20 15:05:40 +0000650 // Keep track of which structures have been printed so far...
651 std::set<const StructType *> StructPrinted;
652
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000653 // Loop over all structures then push them into the stack so they are
654 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +0000655 //
Chris Lattner58d04d42002-09-20 15:18:30 +0000656 Out << "/* Structure contents */\n";
Chris Lattner2db41cd2002-09-20 15:12:13 +0000657 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
658 if (const StructType *STy = dyn_cast<StructType>(I->second))
659 printContainedStructs(STy, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000660}
661
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000662// Push the struct onto the stack and recursively push all structs
663// this one depends on.
Chris Lattner2c601a72002-09-20 15:05:40 +0000664void CWriter::printContainedStructs(const Type *Ty,
665 std::set<const StructType*> &StructPrinted){
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000666 if (const StructType *STy = dyn_cast<StructType>(Ty)){
667 //Check to see if we have already printed this struct
Chris Lattner2c601a72002-09-20 15:05:40 +0000668 if (StructPrinted.count(STy) == 0) {
669 // Print all contained types first...
Chris Lattnera4c047e2002-09-20 14:56:54 +0000670 for (StructType::ElementTypes::const_iterator
671 I = STy->getElementTypes().begin(),
672 E = STy->getElementTypes().end(); I != E; ++I) {
Chris Lattner2c601a72002-09-20 15:05:40 +0000673 const Type *Ty1 = I->get();
Chris Lattnera4c047e2002-09-20 14:56:54 +0000674 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
Chris Lattner2c601a72002-09-20 15:05:40 +0000675 printContainedStructs(Ty1, StructPrinted);
Chris Lattnera4c047e2002-09-20 14:56:54 +0000676 }
677
Chris Lattner2c601a72002-09-20 15:05:40 +0000678 //Print structure type out..
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000679 StructPrinted.insert(STy);
680 string Name = TypeNames[STy];
681 printType(STy, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +0000682 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000683 }
Chris Lattnera4c047e2002-09-20 14:56:54 +0000684
Chris Lattner2c601a72002-09-20 15:05:40 +0000685 // If it is an array, check contained types and continue
686 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000687 const Type *Ty1 = ATy->getElementType();
688 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
Chris Lattner2c601a72002-09-20 15:05:40 +0000689 printContainedStructs(Ty1, StructPrinted);
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000690 }
691}
692
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000693
Chris Lattner4cda8352002-08-20 16:55:48 +0000694void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000695 // If the program provides it's own malloc prototype we don't need
696 // to include the general one.
697 if (getValueName(F) == "malloc")
698 needsMalloc = false;
Chris Lattner16c7bb22002-05-09 02:28:59 +0000699 if (F->hasInternalLinkage()) Out << "static ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000700
701 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +0000702 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000703
Chris Lattner16c7bb22002-05-09 02:28:59 +0000704 // Print out the return type and name...
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000705 printType(F->getReturnType());
Chris Lattner1f02c892002-05-09 20:14:10 +0000706 Out << getValueName(F) << "(";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000707
Chris Lattner16c7bb22002-05-09 02:28:59 +0000708 if (!F->isExternal()) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000709 if (!F->aempty()) {
Chris Lattner4cda8352002-08-20 16:55:48 +0000710 string ArgName;
711 if (F->abegin()->hasName() || !Prototype)
712 ArgName = getValueName(F->abegin());
713
714 printType(F->afront().getType(), ArgName);
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000715
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000716 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
717 I != E; ++I) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000718 Out << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +0000719 if (I->hasName() || !Prototype)
720 ArgName = getValueName(I);
721 else
722 ArgName = "";
723 printType(I->getType(), ArgName);
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000724 }
725 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000726 } else {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000727 // Loop over the arguments, printing them...
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000728 for (FunctionType::ParamTypes::const_iterator I =
Chris Lattner16c7bb22002-05-09 02:28:59 +0000729 FT->getParamTypes().begin(),
730 E = FT->getParamTypes().end(); I != E; ++I) {
731 if (I != FT->getParamTypes().begin()) Out << ", ";
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000732 printType(*I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000733 }
734 }
735
Chris Lattner1f8c4a12002-09-20 22:32:30 +0000736 // Finish printing arguments... if this is a vararg function, print the ...,
737 // unless there are no known types, in which case, we just emit ().
738 //
739 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000740 if (FT->getParamTypes().size()) Out << ", ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000741 Out << "..."; // Output varargs portion of signature!
742 }
Chris Lattner16c7bb22002-05-09 02:28:59 +0000743 Out << ")";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000744}
745
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000746
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000747void CWriter::printFunction(Function *F) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000748 if (F->isExternal()) return;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000749
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000750 Table->incorporateFunction(F);
Chris Lattnerf34ee812002-05-09 03:12:34 +0000751
Chris Lattner4cda8352002-08-20 16:55:48 +0000752 printFunctionSignature(F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000753 Out << " {\n";
754
Chris Lattner497e19a2002-05-09 20:39:03 +0000755 // print local variable information for the function
Chris Lattner7683a122002-05-09 20:33:35 +0000756 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000757 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000758 Out << " ";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000759 printType((*I)->getType(), getValueName(*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000760 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000761 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000762
763 Out << "\n";
764
765 // Scan the function for floating point constants. If any FP constant is used
766 // in the function, we want to redirect it here so that we do not depend on
767 // the precision of the printed form.
768 //
769 unsigned FPCounter = 0;
770 for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
771 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
772 if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
773 double Val = FPC->getValue();
774
775 FPConstantMap[FPC] = FPCounter; // Number the FP constants
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000776
777 if (FPC->getType() == Type::DoubleTy)
778 Out << " const ConstantDoubleTy FloatConstant" << FPCounter++
779 << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
780 << "; /* " << Val << " */\n";
Chris Lattner9c1338b2002-11-07 22:12:53 +0000781 else if (FPC->getType() == Type::FloatTy) {
782 float fVal = Val;
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000783 Out << " const ConstantFloatTy FloatConstant" << FPCounter++
Chris Lattner9c1338b2002-11-07 22:12:53 +0000784 << " = 0x" << std::hex << *(unsigned*)&fVal << std::dec
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000785 << "; /* " << Val << " */\n";
Chris Lattner9c1338b2002-11-07 22:12:53 +0000786 } else
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000787 assert(0 && "Unknown float type!");
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000788 }
789
790 Out << "\n";
Chris Lattner16c7bb22002-05-09 02:28:59 +0000791
792 // print the basic blocks
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000793 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
794 BasicBlock *Prev = BB->getPrev();
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000795
796 // Don't print the label for the basic block if there are no uses, or if the
797 // only terminator use is the precessor basic block's terminator. We have
798 // to scan the use list because PHI nodes use basic blocks too but do not
799 // require a label to be generated.
800 //
801 bool NeedsLabel = false;
802 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
803 UI != UE; ++UI)
804 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
805 if (TI != Prev->getTerminator()) {
806 NeedsLabel = true;
807 break;
808 }
809
810 if (NeedsLabel) Out << getValueName(BB) << ":\n";
811
812 // Output all of the instructions in the basic block...
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000813 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000814 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000815 if (II->getType() != Type::VoidTy)
816 outputLValue(II);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000817 else
818 Out << " ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000819 visit(*II);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000820 Out << ";\n";
821 }
822 }
823
824 // Don't emit prefix or suffix for the terminator...
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000825 visit(*BB->getTerminator());
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000826 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000827
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000828 Out << "}\n\n";
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000829 Table->purgeFunction();
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000830 FPConstantMap.clear();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000831}
832
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000833// Specific Instruction type classes... note that all of the casts are
834// neccesary because we use the instruction classes as opaque types...
835//
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000836void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000837 // Don't output a void return if this is the last basic block in the function
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000838 if (I.getNumOperands() == 0 &&
839 &*--I.getParent()->getParent()->end() == I.getParent() &&
840 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000841 return;
Chris Lattner963b70b2002-05-21 18:05:19 +0000842 }
Chris Lattner44408262002-05-09 03:50:42 +0000843
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000844 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000845 if (I.getNumOperands()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000846 Out << " ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000847 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000848 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000849 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000850}
851
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000852static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
853 // If PHI nodes need copies, we need the copy code...
854 if (isa<PHINode>(To->front()) ||
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000855 From->getNext() != To) // Not directly successor, need goto
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000856 return true;
857
858 // Otherwise we don't need the code.
859 return false;
860}
861
862void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
863 unsigned Indent) {
864 for (BasicBlock::iterator I = Succ->begin();
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000865 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000866 // now we have to do the printing
867 Out << string(Indent, ' ');
868 outputLValue(PN);
869 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
870 Out << "; /* for PHI node */\n";
871 }
872
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000873 if (CurBB->getNext() != Succ) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000874 Out << string(Indent, ' ') << " goto ";
875 writeOperand(Succ);
876 Out << ";\n";
877 }
878}
879
880// Brach instruction printing - Avoid printing out a brach to a basic block that
881// immediately succeeds the current one.
882//
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000883void CWriter::visitBranchInst(BranchInst &I) {
884 if (I.isConditional()) {
885 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000886 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000887 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000888 Out << ") {\n";
889
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000890 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000891
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000892 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000893 Out << " } else {\n";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000894 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000895 }
896 } else {
897 // First goto not neccesary, assume second one is...
898 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000899 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000900 Out << ") {\n";
901
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000902 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000903 }
904
905 Out << " }\n";
906 } else {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000907 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000908 }
909 Out << "\n";
910}
911
912
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000913void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000914 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000915 if (isa<PointerType>(I.getType())) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000916 Out << "(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000917 printType(I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000918 Out << ")";
919 }
920
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000921 if (isa<PointerType>(I.getType())) Out << "(long long)";
922 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000923
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000924 switch (I.getOpcode()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000925 case Instruction::Add: Out << " + "; break;
926 case Instruction::Sub: Out << " - "; break;
927 case Instruction::Mul: Out << "*"; break;
928 case Instruction::Div: Out << "/"; break;
929 case Instruction::Rem: Out << "%"; break;
930 case Instruction::And: Out << " & "; break;
931 case Instruction::Or: Out << " | "; break;
932 case Instruction::Xor: Out << " ^ "; break;
933 case Instruction::SetEQ: Out << " == "; break;
934 case Instruction::SetNE: Out << " != "; break;
935 case Instruction::SetLE: Out << " <= "; break;
936 case Instruction::SetGE: Out << " >= "; break;
937 case Instruction::SetLT: Out << " < "; break;
938 case Instruction::SetGT: Out << " > "; break;
939 case Instruction::Shl : Out << " << "; break;
940 case Instruction::Shr : Out << " >> "; break;
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000941 default: std::cerr << "Invalid operator type!" << I; abort();
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000942 }
943
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000944 if (isa<PointerType>(I.getType())) Out << "(long long)";
945 writeOperand(I.getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000946}
947
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000948void CWriter::visitCastInst(CastInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000949 Out << "(";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000950 printType(I.getType(), string(""),/*ignoreName*/false, /*namedContext*/false);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000951 Out << ")";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000952 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000953}
954
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000955void CWriter::visitCallInst(CallInst &I) {
956 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000957 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
958 const Type *RetTy = FTy->getReturnType();
959
Chris Lattnerfabc8802002-08-26 20:50:09 +0000960 writeOperand(I.getOperand(0));
961 Out << "(";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000962
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000963 if (I.getNumOperands() > 1) {
964 writeOperand(I.getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000965
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000966 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000967 Out << ", ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000968 writeOperand(I.getOperand(op));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000969 }
970 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000971 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000972}
973
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000974void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000975 Out << "(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000976 printType(I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000977 Out << ")malloc(sizeof(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000978 printType(I.getType()->getElementType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000979 Out << ")";
980
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000981 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000982 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000983 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000984 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000985 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000986}
987
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000988void CWriter::visitAllocaInst(AllocaInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000989 Out << "(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000990 printType(I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000991 Out << ") alloca(sizeof(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000992 printType(I.getType()->getElementType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000993 Out << ")";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000994 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000995 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000996 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000997 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000998 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000999}
1000
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001001void CWriter::visitFreeInst(FreeInst &I) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001002 Out << "free(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001003 writeOperand(I.getOperand(0));
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001004 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001005}
1006
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001007void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1008 User::op_iterator E) {
1009 bool HasImplicitAddress = false;
1010 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1011 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1012 HasImplicitAddress = true;
1013 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1014 HasImplicitAddress = true;
1015 Ptr = CPR->getValue(); // Get to the global...
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001016 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001017
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001018 if (I == E) {
1019 if (!HasImplicitAddress)
1020 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001021
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001022 writeOperandInternal(Ptr);
1023 return;
1024 }
1025
1026 const Constant *CI = dyn_cast<Constant>(I->get());
1027 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1028 Out << "(&";
1029
1030 writeOperandInternal(Ptr);
1031
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001032 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001033 Out << ")";
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001034 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1035 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001036
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001037 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1038 "Can only have implicit address with direct accessing");
1039
1040 if (HasImplicitAddress) {
1041 ++I;
1042 } else if (CI && CI->isNullValue() && I+1 != E) {
1043 // Print out the -> operator if possible...
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001044 if ((*(I+1))->getType() == Type::UByteTy) {
1045 Out << (HasImplicitAddress ? "." : "->");
1046 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1047 I += 2;
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001048 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001049 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00001050
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001051 for (; I != E; ++I)
Chris Lattner106ff452002-09-11 01:21:29 +00001052 if ((*I)->getType() == Type::LongTy) {
Vikram S. Adve9d6f13f2002-09-15 21:51:04 +00001053 Out << "[";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001054 writeOperand(*I);
Vikram S. Adve9d6f13f2002-09-15 21:51:04 +00001055 Out << "]";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001056 } else {
Chris Lattner59afbf32002-09-12 20:34:47 +00001057 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001058 }
1059}
1060
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001061void CWriter::visitLoadInst(LoadInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001062 Out << "*";
Chris Lattner5dfe7672002-08-22 22:48:55 +00001063 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001064}
1065
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001066void CWriter::visitStoreInst(StoreInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001067 Out << "*";
Chris Lattner5dfe7672002-08-22 22:48:55 +00001068 writeOperand(I.getPointerOperand());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001069 Out << " = ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001070 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001071}
1072
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001073void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001074 Out << "&";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001075 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001076}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001077
1078//===----------------------------------------------------------------------===//
1079// External Interface declaration
1080//===----------------------------------------------------------------------===//
1081
Chris Lattner0e9f93e2002-08-31 00:29:16 +00001082Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }