blob: 23bd41d8dd089f2851c9b1079e4db06022bc58d2 [file] [log] [blame]
Chris Lattner3af3ba82002-05-09 21:31:18 +00001//===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
Misha Brukmand6a29a52005-04-20 16:05:03 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmand6a29a52005-04-20 16:05:03 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00009//
Chris Lattner897bf0d2004-02-13 06:18:21 +000010// This library converts LLVM code to C code, compilable by GCC and other C
11// compilers.
Chris Lattner16c7bb22002-05-09 02:28:59 +000012//
Chris Lattneredd8ce12003-05-03 03:14:35 +000013//===----------------------------------------------------------------------===//
Chris Lattner84e66652003-05-03 07:11:00 +000014
Chris Lattnerf31182a2004-02-13 23:18:48 +000015#include "CTargetMachine.h"
Chris Lattner0c54d892006-05-23 23:39:48 +000016#include "llvm/CallingConv.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000017#include "llvm/Constants.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000018#include "llvm/DerivedTypes.h"
19#include "llvm/Module.h"
Chris Lattnera9f5e052003-04-22 20:19:52 +000020#include "llvm/Instructions.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000021#include "llvm/Pass.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000022#include "llvm/PassManager.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000023#include "llvm/SymbolTable.h"
Chris Lattner18ac3c82003-05-08 18:41:45 +000024#include "llvm/Intrinsics.h"
Jim Laskey580418e2006-03-23 18:08:29 +000025#include "llvm/IntrinsicInst.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000026#include "llvm/Analysis/ConstantsScanner.h"
Chris Lattnercb3ad012004-05-09 20:41:32 +000027#include "llvm/Analysis/FindUsedTypes.h"
28#include "llvm/Analysis/LoopInfo.h"
Chris Lattner30483732004-06-20 07:49:54 +000029#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000030#include "llvm/Transforms/Scalar.h"
Chris Lattnerd36c9702004-07-11 02:48:49 +000031#include "llvm/Target/TargetMachineRegistry.h"
Chris Lattner23e90702003-11-25 20:49:55 +000032#include "llvm/Support/CallSite.h"
Chris Lattnera05e0ec2004-05-09 03:42:48 +000033#include "llvm/Support/CFG.h"
Chris Lattner23e90702003-11-25 20:49:55 +000034#include "llvm/Support/GetElementPtrTypeIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000035#include "llvm/Support/InstVisitor.h"
Brian Gaeke49a178b2003-07-25 20:21:06 +000036#include "llvm/Support/Mangler.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000037#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000038#include "llvm/ADT/StringExtras.h"
Chris Lattner67c2d182005-03-18 16:12:37 +000039#include "llvm/ADT/STLExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000040#include "llvm/Support/MathExtras.h"
41#include "llvm/Config/config.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000042#include <algorithm>
Reid Spencer954da372004-07-04 12:19:56 +000043#include <iostream>
Duraid Madinad2dec7d2005-12-27 10:40:34 +000044#include <ios>
Nick Hildenbrandt98502372002-11-18 20:55:50 +000045#include <sstream>
Chris Lattner897bf0d2004-02-13 06:18:21 +000046using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000047
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000048namespace {
Chris Lattnerd36c9702004-07-11 02:48:49 +000049 // Register the target.
Chris Lattner71d24aa2004-07-11 03:27:42 +000050 RegisterTarget<CTargetMachine> X("c", " C backend");
Chris Lattnerd36c9702004-07-11 02:48:49 +000051
Chris Lattnerf9a05322006-02-13 22:22:42 +000052 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
53 /// any unnamed structure types that are used by the program, and merges
54 /// external functions with the same name.
Chris Lattner68758072004-05-09 06:20:51 +000055 ///
Chris Lattnerf9a05322006-02-13 22:22:42 +000056 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
Chris Lattner68758072004-05-09 06:20:51 +000057 void getAnalysisUsage(AnalysisUsage &AU) const {
58 AU.addRequired<FindUsedTypes>();
59 }
60
61 virtual const char *getPassName() const {
62 return "C backend type canonicalizer";
63 }
64
Chris Lattnerb12914b2004-09-20 04:48:05 +000065 virtual bool runOnModule(Module &M);
Chris Lattner68758072004-05-09 06:20:51 +000066 };
Misha Brukmand6a29a52005-04-20 16:05:03 +000067
Chris Lattner68758072004-05-09 06:20:51 +000068 /// CWriter - This class is the main chunk of code that converts an LLVM
69 /// module to a C translation unit.
70 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
Misha Brukmand6a29a52005-04-20 16:05:03 +000071 std::ostream &Out;
Chris Lattnerbc641b92006-03-23 05:43:16 +000072 DefaultIntrinsicLowering IL;
Brian Gaeked9fb37a2003-07-24 20:20:44 +000073 Mangler *Mang;
Chris Lattnercb3ad012004-05-09 20:41:32 +000074 LoopInfo *LI;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000075 const Module *TheModule;
Chris Lattneredd8ce12003-05-03 03:14:35 +000076 std::map<const Type *, std::string> TypeNames;
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +000077
Chris Lattneredd8ce12003-05-03 03:14:35 +000078 std::map<const ConstantFP *, unsigned> FPConstantMap;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000079 public:
Chris Lattnerbc641b92006-03-23 05:43:16 +000080 CWriter(std::ostream &o) : Out(o) {}
Chris Lattner0e9f93e2002-08-31 00:29:16 +000081
Chris Lattner94f4f8e2004-02-13 23:00:29 +000082 virtual const char *getPassName() const { return "C backend"; }
Chris Lattner0e9f93e2002-08-31 00:29:16 +000083
Chris Lattnercb3ad012004-05-09 20:41:32 +000084 void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<LoopInfo>();
86 AU.setPreservesAll();
87 }
88
Chris Lattner68758072004-05-09 06:20:51 +000089 virtual bool doInitialization(Module &M);
Chris Lattner0e9f93e2002-08-31 00:29:16 +000090
Chris Lattner68758072004-05-09 06:20:51 +000091 bool runOnFunction(Function &F) {
Chris Lattnercb3ad012004-05-09 20:41:32 +000092 LI = &getAnalysis<LoopInfo>();
93
Chris Lattner3150e2d2004-12-05 06:49:44 +000094 // Get rid of intrinsics we can't handle.
95 lowerIntrinsics(F);
96
Chris Lattner68758072004-05-09 06:20:51 +000097 // Output all floating point constants that cannot be printed accurately.
98 printFloatingPointConstants(F);
Chris Lattner3150e2d2004-12-05 06:49:44 +000099
100 // Ensure that no local symbols conflict with global symbols.
101 F.renameLocalSymbols();
102
Chris Lattner68758072004-05-09 06:20:51 +0000103 printFunction(F);
104 FPConstantMap.clear();
105 return false;
106 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000107
Chris Lattner68758072004-05-09 06:20:51 +0000108 virtual bool doFinalization(Module &M) {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000109 // Free memory...
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000110 delete Mang;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000111 TypeNames.clear();
Chris Lattnercb3ad012004-05-09 20:41:32 +0000112 return false;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000113 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000114
Chris Lattneredd8ce12003-05-03 03:14:35 +0000115 std::ostream &printType(std::ostream &Out, const Type *Ty,
116 const std::string &VariableName = "",
Chris Lattner7635ea42003-11-03 01:01:59 +0000117 bool IgnoreName = false);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000118
Chris Lattner0c54d892006-05-23 23:39:48 +0000119 void printStructReturnPointerFunctionType(std::ostream &Out,
120 const PointerType *Ty);
121
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000122 void writeOperand(Value *Operand);
123 void writeOperandInternal(Value *Operand);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000124
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000125 private :
Chris Lattnerc2421432004-05-09 04:30:20 +0000126 void lowerIntrinsics(Function &F);
Chris Lattner4ef51372004-02-14 00:31:10 +0000127
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000128 void printModule(Module *M);
Chris Lattner68758072004-05-09 06:20:51 +0000129 void printModuleTypes(const SymbolTable &ST);
Chris Lattner2c601a72002-09-20 15:05:40 +0000130 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
Chris Lattner68758072004-05-09 06:20:51 +0000131 void printFloatingPointConstants(Function &F);
Chris Lattner4cda8352002-08-20 16:55:48 +0000132 void printFunctionSignature(const Function *F, bool Prototype);
133
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000134 void printFunction(Function &);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000135 void printBasicBlock(BasicBlock *BB);
136 void printLoop(Loop *L);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000137
Chris Lattner6d492922002-08-19 21:32:41 +0000138 void printConstant(Constant *CPV);
139 void printConstantArray(ConstantArray *CPA);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000140 void printConstantPacked(ConstantPacked *CP);
Chris Lattner6d492922002-08-19 21:32:41 +0000141
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000142 // isInlinableInst - Attempt to inline instructions into their uses to build
143 // trees as much as possible. To do this, we have to consistently decide
144 // what is acceptable to inline, so that variable declarations don't get
145 // printed and an extra copy of the expr is not emitted.
146 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000147 static bool isInlinableInst(const Instruction &I) {
Chris Lattner433e25a2004-05-20 20:25:50 +0000148 // Always inline setcc instructions, even if they are shared by multiple
149 // expressions. GCC generates horrible code if we don't.
150 if (isa<SetCondInst>(I)) return true;
151
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000152 // Must be an expression, must be used exactly once. If it is dead, we
153 // emit it inline where it would go.
Chris Lattnerfd059242003-10-15 16:48:29 +0000154 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
Misha Brukmand6a29a52005-04-20 16:05:03 +0000155 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Andrew Lenharth558bc882005-06-18 18:34:52 +0000156 isa<LoadInst>(I) || isa<VAArgInst>(I))
Chris Lattnerd4e8d312003-07-23 20:45:31 +0000157 // Don't inline a load across a store or other bad things!
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000158 return false;
159
160 // Only inline instruction it it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000161 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000162 }
163
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000164 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
165 // variables which are accessed with the & operator. This causes GCC to
166 // generate significantly better code than to emit alloca calls directly.
167 //
168 static const AllocaInst *isDirectAlloca(const Value *V) {
169 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
170 if (!AI) return false;
171 if (AI->isArrayAllocation())
172 return 0; // FIXME: we can also inline fixed size array allocas!
Chris Lattner02a3be02003-09-20 14:39:18 +0000173 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000174 return 0;
175 return AI;
176 }
177
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000178 // Instruction visitation functions
179 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000180
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000181 void visitReturnInst(ReturnInst &I);
182 void visitBranchInst(BranchInst &I);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000183 void visitSwitchInst(SwitchInst &I);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000184 void visitInvokeInst(InvokeInst &I) {
185 assert(0 && "Lowerinvoke pass didn't work!");
186 }
187
188 void visitUnwindInst(UnwindInst &I) {
189 assert(0 && "Lowerinvoke pass didn't work!");
190 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000191 void visitUnreachableInst(UnreachableInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000192
Chris Lattner84e66652003-05-03 07:11:00 +0000193 void visitPHINode(PHINode &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000194 void visitBinaryOperator(Instruction &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000195
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000196 void visitCastInst (CastInst &I);
Chris Lattner9f24a072004-03-12 05:52:14 +0000197 void visitSelectInst(SelectInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000198 void visitCallInst (CallInst &I);
199 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000200
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000201 void visitMallocInst(MallocInst &I);
202 void visitAllocaInst(AllocaInst &I);
203 void visitFreeInst (FreeInst &I);
204 void visitLoadInst (LoadInst &I);
205 void visitStoreInst (StoreInst &I);
206 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner4d45bd02003-10-18 05:57:43 +0000207 void visitVAArgInst (VAArgInst &I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000208
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000209 void visitInstruction(Instruction &I) {
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000210 std::cerr << "C Writer does not know about " << I;
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000211 abort();
212 }
213
214 void outputLValue(Instruction *I) {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000215 Out << " " << Mang->getValueName(I) << " = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000216 }
Chris Lattnercb3ad012004-05-09 20:41:32 +0000217
218 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
John Criswell57bbfce2004-10-20 14:38:39 +0000219 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
220 BasicBlock *Successor, unsigned Indent);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000221 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
222 unsigned Indent);
Chris Lattner23e90702003-11-25 20:49:55 +0000223 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
224 gep_type_iterator E);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000225 };
Chris Lattner4ef51372004-02-14 00:31:10 +0000226}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000227
Chris Lattner68758072004-05-09 06:20:51 +0000228/// This method inserts names for any unnamed structure types that are used by
229/// the program, and removes names from structure types that are not used by the
230/// program.
231///
Chris Lattnerf9a05322006-02-13 22:22:42 +0000232bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
Chris Lattner68758072004-05-09 06:20:51 +0000233 // Get a set of types that are used by the program...
234 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000235
Chris Lattner68758072004-05-09 06:20:51 +0000236 // Loop over the module symbol table, removing types from UT that are
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000237 // already named, and removing names for types that are not used.
Chris Lattner68758072004-05-09 06:20:51 +0000238 //
239 SymbolTable &MST = M.getSymbolTable();
Reid Spencer9231ac82004-05-25 08:53:40 +0000240 for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
241 TI != TE; ) {
242 SymbolTable::type_iterator I = TI++;
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000243
244 // If this is not used, remove it from the symbol table.
245 std::set<const Type *>::iterator UTI = UT.find(I->second);
246 if (UTI == UT.end())
247 MST.remove(I);
248 else
249 UT.erase(UTI); // Only keep one name for this type.
Reid Spencer9231ac82004-05-25 08:53:40 +0000250 }
Chris Lattner68758072004-05-09 06:20:51 +0000251
252 // UT now contains types that are not named. Loop over it, naming
253 // structure types.
254 //
255 bool Changed = false;
Chris Lattner9d1af972004-05-28 05:47:27 +0000256 unsigned RenameCounter = 0;
Chris Lattner68758072004-05-09 06:20:51 +0000257 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
258 I != E; ++I)
259 if (const StructType *ST = dyn_cast<StructType>(*I)) {
Chris Lattner9d1af972004-05-28 05:47:27 +0000260 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
261 ++RenameCounter;
Chris Lattner68758072004-05-09 06:20:51 +0000262 Changed = true;
263 }
Chris Lattnerf9a05322006-02-13 22:22:42 +0000264
265
266 // Loop over all external functions and globals. If we have two with
267 // identical names, merge them.
268 // FIXME: This code should disappear when we don't allow values with the same
269 // names when they have different types!
270 std::map<std::string, GlobalValue*> ExtSymbols;
271 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
272 Function *GV = I++;
273 if (GV->isExternal() && GV->hasName()) {
274 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
275 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
276 if (!X.second) {
277 // Found a conflict, replace this global with the previous one.
278 GlobalValue *OldGV = X.first->second;
279 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
280 GV->eraseFromParent();
281 Changed = true;
282 }
283 }
284 }
285 // Do the same for globals.
286 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
287 I != E;) {
288 GlobalVariable *GV = I++;
289 if (GV->isExternal() && GV->hasName()) {
290 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
291 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
292 if (!X.second) {
293 // Found a conflict, replace this global with the previous one.
294 GlobalValue *OldGV = X.first->second;
295 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
296 GV->eraseFromParent();
297 Changed = true;
298 }
299 }
300 }
301
Chris Lattner68758072004-05-09 06:20:51 +0000302 return Changed;
303}
304
Chris Lattner0c54d892006-05-23 23:39:48 +0000305/// printStructReturnPointerFunctionType - This is like printType for a struct
306/// return type, except, instead of printing the type as void (*)(Struct*, ...)
307/// print it as "Struct (*)(...)", for struct return functions.
308void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
309 const PointerType *TheTy) {
310 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
311 std::stringstream FunctionInnards;
312 FunctionInnards << " (*) (";
313 bool PrintedType = false;
314
315 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
316 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
317 for (++I; I != E; ++I) {
318 if (PrintedType)
319 FunctionInnards << ", ";
320 printType(FunctionInnards, *I, "");
321 PrintedType = true;
322 }
323 if (FTy->isVarArg()) {
324 if (PrintedType)
325 FunctionInnards << ", ...";
326 } else if (!PrintedType) {
327 FunctionInnards << "void";
328 }
329 FunctionInnards << ')';
330 std::string tstr = FunctionInnards.str();
331 printType(Out, RetTy, tstr);
332}
333
Chris Lattner68758072004-05-09 06:20:51 +0000334
Chris Lattner83c57752002-08-19 22:17:53 +0000335// Pass the Type* and the variable name and this prints out the variable
336// declaration.
337//
Chris Lattneredd8ce12003-05-03 03:14:35 +0000338std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
339 const std::string &NameSoFar,
Chris Lattner7635ea42003-11-03 01:01:59 +0000340 bool IgnoreName) {
Chris Lattner83c57752002-08-19 22:17:53 +0000341 if (Ty->isPrimitiveType())
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000342 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000343 case Type::VoidTyID: return Out << "void " << NameSoFar;
344 case Type::BoolTyID: return Out << "bool " << NameSoFar;
345 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
346 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
347 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
348 case Type::ShortTyID: return Out << "short " << NameSoFar;
349 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
350 case Type::IntTyID: return Out << "int " << NameSoFar;
351 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
352 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
353 case Type::FloatTyID: return Out << "float " << NameSoFar;
354 case Type::DoubleTyID: return Out << "double " << NameSoFar;
355 default :
Chris Lattner76e2df22004-07-15 02:14:30 +0000356 std::cerr << "Unknown primitive type: " << *Ty << "\n";
Chris Lattner83c57752002-08-19 22:17:53 +0000357 abort();
358 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000359
Chris Lattner83c57752002-08-19 22:17:53 +0000360 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000361 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +0000362 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000363 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000364 }
Chris Lattner83c57752002-08-19 22:17:53 +0000365
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000366 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000367 case Type::FunctionTyID: {
Chris Lattner0c54d892006-05-23 23:39:48 +0000368 const FunctionType *FTy = cast<FunctionType>(Ty);
Misha Brukmand6a29a52005-04-20 16:05:03 +0000369 std::stringstream FunctionInnards;
Joel Stanley54f60322003-06-25 04:52:09 +0000370 FunctionInnards << " (" << NameSoFar << ") (";
Chris Lattner0c54d892006-05-23 23:39:48 +0000371 for (FunctionType::param_iterator I = FTy->param_begin(),
372 E = FTy->param_end(); I != E; ++I) {
373 if (I != FTy->param_begin())
Joel Stanley54f60322003-06-25 04:52:09 +0000374 FunctionInnards << ", ";
375 printType(FunctionInnards, *I, "");
Chris Lattner83c57752002-08-19 22:17:53 +0000376 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000377 if (FTy->isVarArg()) {
378 if (FTy->getNumParams())
Reid Spencer9231ac82004-05-25 08:53:40 +0000379 FunctionInnards << ", ...";
Chris Lattner0c54d892006-05-23 23:39:48 +0000380 } else if (!FTy->getNumParams()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000381 FunctionInnards << "void";
Chris Lattner83c57752002-08-19 22:17:53 +0000382 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000383 FunctionInnards << ')';
Joel Stanley54f60322003-06-25 04:52:09 +0000384 std::string tstr = FunctionInnards.str();
Chris Lattner0c54d892006-05-23 23:39:48 +0000385 printType(Out, FTy->getReturnType(), tstr);
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000386 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000387 }
388 case Type::StructTyID: {
389 const StructType *STy = cast<StructType>(Ty);
390 Out << NameSoFar + " {\n";
391 unsigned Idx = 0;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000392 for (StructType::element_iterator I = STy->element_begin(),
393 E = STy->element_end(); I != E; ++I) {
Chris Lattner83c57752002-08-19 22:17:53 +0000394 Out << " ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000395 printType(Out, *I, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000396 Out << ";\n";
397 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000398 return Out << '}';
Misha Brukmand6a29a52005-04-20 16:05:03 +0000399 }
Chris Lattner83c57752002-08-19 22:17:53 +0000400
401 case Type::PointerTyID: {
402 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000403 std::string ptrName = "*" + NameSoFar;
404
Robert Bocchinob78e8382006-01-20 20:43:57 +0000405 if (isa<ArrayType>(PTy->getElementType()) ||
406 isa<PackedType>(PTy->getElementType()))
Chris Lattner8917d362003-11-03 04:31:54 +0000407 ptrName = "(" + ptrName + ")";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000408
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000409 return printType(Out, PTy->getElementType(), ptrName);
Misha Brukman8f9f9a22003-07-21 16:34:35 +0000410 }
Chris Lattner83c57752002-08-19 22:17:53 +0000411
412 case Type::ArrayTyID: {
413 const ArrayType *ATy = cast<ArrayType>(Ty);
414 unsigned NumElements = ATy->getNumElements();
Chris Lattner3e3b6f72004-12-15 23:13:15 +0000415 if (NumElements == 0) NumElements = 1;
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000416 return printType(Out, ATy->getElementType(),
Chris Lattner83c57752002-08-19 22:17:53 +0000417 NameSoFar + "[" + utostr(NumElements) + "]");
418 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000419
Robert Bocchinob78e8382006-01-20 20:43:57 +0000420 case Type::PackedTyID: {
421 const PackedType *PTy = cast<PackedType>(Ty);
422 unsigned NumElements = PTy->getNumElements();
423 if (NumElements == 0) NumElements = 1;
424 return printType(Out, PTy->getElementType(),
425 NameSoFar + "[" + utostr(NumElements) + "]");
426 }
427
Chris Lattner04b72c82002-10-16 00:08:22 +0000428 case Type::OpaqueTyID: {
429 static int Count = 0;
Chris Lattneredd8ce12003-05-03 03:14:35 +0000430 std::string TyName = "struct opaque_" + itostr(Count++);
Chris Lattner04b72c82002-10-16 00:08:22 +0000431 assert(TypeNames.find(Ty) == TypeNames.end());
432 TypeNames[Ty] = TyName;
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000433 return Out << TyName << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000434 }
Chris Lattner83c57752002-08-19 22:17:53 +0000435 default:
436 assert(0 && "Unhandled case in getTypeProps!");
437 abort();
438 }
439
440 return Out;
441}
442
Chris Lattner6d492922002-08-19 21:32:41 +0000443void CWriter::printConstantArray(ConstantArray *CPA) {
444
445 // As a special case, print the array as a string if it is an array of
446 // ubytes or an array of sbytes with positive values.
Misha Brukmand6a29a52005-04-20 16:05:03 +0000447 //
Chris Lattner6d492922002-08-19 21:32:41 +0000448 const Type *ETy = CPA->getType()->getElementType();
449 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
450
451 // Make sure the last character is a null char, as automatically added by C
Chris Lattner02da6c02003-06-16 12:09:09 +0000452 if (isString && (CPA->getNumOperands() == 0 ||
453 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattner6d492922002-08-19 21:32:41 +0000454 isString = false;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000455
Chris Lattner6d492922002-08-19 21:32:41 +0000456 if (isString) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000457 Out << '\"';
Chris Lattner02da6c02003-06-16 12:09:09 +0000458 // Keep track of whether the last number was a hexadecimal escape
459 bool LastWasHex = false;
460
Chris Lattner6d492922002-08-19 21:32:41 +0000461 // Do not include the last character, which we know is null
462 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000463 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000464
Chris Lattner02da6c02003-06-16 12:09:09 +0000465 // Print it out literally if it is a printable character. The only thing
466 // to be careful about is when the last letter output was a hex escape
467 // code, in which case we have to be careful not to print out hex digits
Chris Lattnerda920902003-06-16 12:21:19 +0000468 // explicitly (the C compiler thinks it is a continuation of the previous
469 // character, sheesh...)
Chris Lattner02da6c02003-06-16 12:09:09 +0000470 //
471 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
472 LastWasHex = false;
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000473 if (C == '"' || C == '\\')
474 Out << "\\" << C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000475 else
476 Out << C;
Chris Lattner6d492922002-08-19 21:32:41 +0000477 } else {
Chris Lattner02da6c02003-06-16 12:09:09 +0000478 LastWasHex = false;
Chris Lattner6d492922002-08-19 21:32:41 +0000479 switch (C) {
480 case '\n': Out << "\\n"; break;
481 case '\t': Out << "\\t"; break;
482 case '\r': Out << "\\r"; break;
483 case '\v': Out << "\\v"; break;
484 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000485 case '\"': Out << "\\\""; break;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000486 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000487 default:
488 Out << "\\x";
Chris Lattner02da6c02003-06-16 12:09:09 +0000489 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
490 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
491 LastWasHex = true;
Chris Lattner6d492922002-08-19 21:32:41 +0000492 break;
493 }
494 }
495 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000496 Out << '\"';
Chris Lattner6d492922002-08-19 21:32:41 +0000497 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000498 Out << '{';
Chris Lattner6d492922002-08-19 21:32:41 +0000499 if (CPA->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000500 Out << ' ';
Chris Lattner6d492922002-08-19 21:32:41 +0000501 printConstant(cast<Constant>(CPA->getOperand(0)));
502 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
503 Out << ", ";
504 printConstant(cast<Constant>(CPA->getOperand(i)));
505 }
506 }
507 Out << " }";
508 }
509}
510
Robert Bocchinob78e8382006-01-20 20:43:57 +0000511void CWriter::printConstantPacked(ConstantPacked *CP) {
512 Out << '{';
513 if (CP->getNumOperands()) {
514 Out << ' ';
515 printConstant(cast<Constant>(CP->getOperand(0)));
516 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
517 Out << ", ";
518 printConstant(cast<Constant>(CP->getOperand(i)));
519 }
520 }
521 Out << " }";
522}
523
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000524// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
525// textually as a double (rather than as a reference to a stack-allocated
526// variable). We decide this by converting CFP to a string and back into a
527// double, and then checking whether the conversion results in a bit-equal
528// double to the original value of CFP. This depends on us and the target C
529// compiler agreeing on the conversion process (which is pretty likely since we
530// only deal in IEEE FP).
531//
Chris Lattnercb3ad012004-05-09 20:41:32 +0000532static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Chris Lattner4946a8c2003-10-13 17:13:53 +0000533#if HAVE_PRINTF_A
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000534 char Buffer[100];
535 sprintf(Buffer, "%a", CFP->getValue());
536
537 if (!strncmp(Buffer, "0x", 2) ||
538 !strncmp(Buffer, "-0x", 3) ||
539 !strncmp(Buffer, "+0x", 3))
540 return atof(Buffer) == CFP->getValue();
541 return false;
542#else
Brian Gaekeb471a232003-06-17 23:55:35 +0000543 std::string StrVal = ftostr(CFP->getValue());
Chris Lattner9860e772003-10-12 04:36:29 +0000544
545 while (StrVal[0] == ' ')
546 StrVal.erase(StrVal.begin());
547
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000548 // Check to make sure that the stringized number is not some string like "Inf"
549 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaekeb471a232003-06-17 23:55:35 +0000550 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
551 ((StrVal[0] == '-' || StrVal[0] == '+') &&
552 (StrVal[1] >= '0' && StrVal[1] <= '9')))
553 // Reparse stringized version!
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000554 return atof(StrVal.c_str()) == CFP->getValue();
Brian Gaekeb471a232003-06-17 23:55:35 +0000555 return false;
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000556#endif
Brian Gaekeb471a232003-06-17 23:55:35 +0000557}
Chris Lattner6d492922002-08-19 21:32:41 +0000558
559// printConstant - The LLVM Constant to C Constant converter.
560void CWriter::printConstant(Constant *CPV) {
561 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
562 switch (CE->getOpcode()) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000563 case Instruction::Cast:
564 Out << "((";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000565 printType(Out, CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000566 Out << ')';
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000567 printConstant(CE->getOperand(0));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000568 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000569 return;
570
571 case Instruction::GetElementPtr:
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000572 Out << "(&(";
Chris Lattner23e90702003-11-25 20:49:55 +0000573 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
574 gep_type_end(CPV));
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000575 Out << "))";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000576 return;
Chris Lattner6683dbf2004-04-01 05:28:26 +0000577 case Instruction::Select:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000578 Out << '(';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000579 printConstant(CE->getOperand(0));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000580 Out << '?';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000581 printConstant(CE->getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000582 Out << ':';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000583 printConstant(CE->getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000584 Out << ')';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000585 return;
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000586 case Instruction::Add:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000587 case Instruction::Sub:
Chris Lattner29255922003-08-14 19:19:53 +0000588 case Instruction::Mul:
589 case Instruction::Div:
590 case Instruction::Rem:
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000591 case Instruction::And:
592 case Instruction::Or:
593 case Instruction::Xor:
Chris Lattner29255922003-08-14 19:19:53 +0000594 case Instruction::SetEQ:
595 case Instruction::SetNE:
596 case Instruction::SetLT:
597 case Instruction::SetLE:
598 case Instruction::SetGT:
599 case Instruction::SetGE:
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000600 case Instruction::Shl:
601 case Instruction::Shr:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000602 Out << '(';
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000603 printConstant(CE->getOperand(0));
Chris Lattner29255922003-08-14 19:19:53 +0000604 switch (CE->getOpcode()) {
605 case Instruction::Add: Out << " + "; break;
606 case Instruction::Sub: Out << " - "; break;
607 case Instruction::Mul: Out << " * "; break;
608 case Instruction::Div: Out << " / "; break;
609 case Instruction::Rem: Out << " % "; break;
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000610 case Instruction::And: Out << " & "; break;
611 case Instruction::Or: Out << " | "; break;
612 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner29255922003-08-14 19:19:53 +0000613 case Instruction::SetEQ: Out << " == "; break;
614 case Instruction::SetNE: Out << " != "; break;
615 case Instruction::SetLT: Out << " < "; break;
616 case Instruction::SetLE: Out << " <= "; break;
617 case Instruction::SetGT: Out << " > "; break;
618 case Instruction::SetGE: Out << " >= "; break;
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000619 case Instruction::Shl: Out << " << "; break;
620 case Instruction::Shr: Out << " >> "; break;
Chris Lattner29255922003-08-14 19:19:53 +0000621 default: assert(0 && "Illegal opcode here!");
622 }
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000623 printConstant(CE->getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000624 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000625 return;
626
Chris Lattner6d492922002-08-19 21:32:41 +0000627 default:
628 std::cerr << "CWriter Error: Unhandled constant expression: "
Chris Lattner76e2df22004-07-15 02:14:30 +0000629 << *CE << "\n";
Chris Lattner6d492922002-08-19 21:32:41 +0000630 abort();
631 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000632 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
Chris Lattner665825e2004-10-17 17:48:59 +0000633 Out << "((";
634 printType(Out, CPV->getType());
635 Out << ")/*UNDEF*/0)";
Chris Lattnera9d12c02004-10-16 18:12:13 +0000636 return;
Chris Lattner6d492922002-08-19 21:32:41 +0000637 }
638
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000639 switch (CPV->getType()->getTypeID()) {
Chris Lattner6d492922002-08-19 21:32:41 +0000640 case Type::BoolTyID:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000641 Out << (CPV == ConstantBool::False ? '0' : '1'); break;
Chris Lattner6d492922002-08-19 21:32:41 +0000642 case Type::SByteTyID:
643 case Type::ShortTyID:
Chris Lattner6d492922002-08-19 21:32:41 +0000644 Out << cast<ConstantSInt>(CPV)->getValue(); break;
Chris Lattner45343ea2003-05-12 15:39:31 +0000645 case Type::IntTyID:
646 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
Chris Lattner40e7c352004-11-30 21:33:58 +0000647 Out << "((int)0x80000000U)"; // Handle MININT specially to avoid warning
Chris Lattner45343ea2003-05-12 15:39:31 +0000648 else
649 Out << cast<ConstantSInt>(CPV)->getValue();
650 break;
651
Chris Lattner6d492922002-08-19 21:32:41 +0000652 case Type::LongTyID:
Chris Lattner40e7c352004-11-30 21:33:58 +0000653 if (cast<ConstantSInt>(CPV)->isMinValue())
654 Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
655 else
656 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000657
658 case Type::UByteTyID:
659 case Type::UShortTyID:
660 Out << cast<ConstantUInt>(CPV)->getValue(); break;
661 case Type::UIntTyID:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000662 Out << cast<ConstantUInt>(CPV)->getValue() << 'u'; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000663 case Type::ULongTyID:
664 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
665
666 case Type::FloatTyID:
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000667 case Type::DoubleTyID: {
668 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattneredd8ce12003-05-03 03:14:35 +0000669 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000670 if (I != FPConstantMap.end()) {
671 // Because of FP precision problems we must load from a stack allocated
672 // value that holds the value in hex.
673 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000674 << "*)&FPConstant" << I->second << ')';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000675 } else {
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000676 if (IsNAN(FPC->getValue())) {
677 // The value is NaN
Misha Brukmand6a29a52005-04-20 16:05:03 +0000678
Brian Gaeke8a702e82004-08-25 19:00:42 +0000679 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
680 // it's 0x7ff4.
681 const unsigned long QuietNaN = 0x7ff8UL;
682 const unsigned long SignalNaN = 0x7ff4UL;
683
684 // We need to grab the first part of the FP #
Brian Gaeke8a702e82004-08-25 19:00:42 +0000685 char Buffer[100];
686
Jim Laskeycb6682f2005-08-17 19:34:49 +0000687 uint64_t ll = DoubleToBits(FPC->getValue());
Reid Spencer2bc320d2006-05-31 22:26:11 +0000688 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
Brian Gaeke8a702e82004-08-25 19:00:42 +0000689
690 std::string Num(&Buffer[0], &Buffer[6]);
691 unsigned long Val = strtoul(Num.c_str(), 0, 16);
692
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000693 if (FPC->getType() == Type::FloatTy)
Brian Gaeke8a702e82004-08-25 19:00:42 +0000694 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
695 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000696 else
Brian Gaeke8a702e82004-08-25 19:00:42 +0000697 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
698 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000699 } else if (IsInf(FPC->getValue())) {
700 // The value is Inf
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000701 if (FPC->getValue() < 0) Out << '-';
Brian Gaeke8a702e82004-08-25 19:00:42 +0000702 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
703 << " /*inf*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000704 } else {
Brian Gaeke07b52b32004-08-25 19:37:26 +0000705 std::string Num;
706#if HAVE_PRINTF_A
707 // Print out the constant as a floating point number.
708 char Buffer[100];
709 sprintf(Buffer, "%a", FPC->getValue());
710 Num = Buffer;
711#else
712 Num = ftostr(FPC->getValue());
713#endif
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000714 Out << Num;
715 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000716 }
717 break;
718 }
Chris Lattner6d492922002-08-19 21:32:41 +0000719
720 case Type::ArrayTyID:
Chris Lattnera9d12c02004-10-16 18:12:13 +0000721 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000722 const ArrayType *AT = cast<ArrayType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000723 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000724 if (AT->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000725 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000726 Constant *CZ = Constant::getNullValue(AT->getElementType());
727 printConstant(CZ);
728 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
729 Out << ", ";
730 printConstant(CZ);
731 }
732 }
733 Out << " }";
734 } else {
735 printConstantArray(cast<ConstantArray>(CPV));
736 }
Chris Lattner6d492922002-08-19 21:32:41 +0000737 break;
738
Robert Bocchinob78e8382006-01-20 20:43:57 +0000739 case Type::PackedTyID:
740 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
741 const PackedType *AT = cast<PackedType>(CPV->getType());
742 Out << '{';
743 if (AT->getNumElements()) {
744 Out << ' ';
745 Constant *CZ = Constant::getNullValue(AT->getElementType());
746 printConstant(CZ);
747 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
748 Out << ", ";
749 printConstant(CZ);
750 }
751 }
752 Out << " }";
753 } else {
754 printConstantPacked(cast<ConstantPacked>(CPV));
755 }
756 break;
757
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000758 case Type::StructTyID:
Chris Lattnera9d12c02004-10-16 18:12:13 +0000759 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000760 const StructType *ST = cast<StructType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000761 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000762 if (ST->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000763 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000764 printConstant(Constant::getNullValue(ST->getElementType(0)));
765 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
766 Out << ", ";
767 printConstant(Constant::getNullValue(ST->getElementType(i)));
768 }
Chris Lattner6d492922002-08-19 21:32:41 +0000769 }
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000770 Out << " }";
771 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000772 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000773 if (CPV->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000774 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000775 printConstant(cast<Constant>(CPV->getOperand(0)));
776 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
777 Out << ", ";
778 printConstant(cast<Constant>(CPV->getOperand(i)));
779 }
780 }
781 Out << " }";
Chris Lattner6d492922002-08-19 21:32:41 +0000782 }
Chris Lattner6d492922002-08-19 21:32:41 +0000783 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000784
785 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000786 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattnercf135cb2003-06-02 03:10:53 +0000787 Out << "((";
788 printType(Out, CPV->getType());
789 Out << ")/*NULL*/0)";
Chris Lattner6d492922002-08-19 21:32:41 +0000790 break;
Reid Spencer518310c2004-07-18 00:44:37 +0000791 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
792 writeOperand(GV);
Chris Lattner6d492922002-08-19 21:32:41 +0000793 break;
794 }
795 // FALL THROUGH
796 default:
Chris Lattner76e2df22004-07-15 02:14:30 +0000797 std::cerr << "Unknown constant type: " << *CPV << "\n";
Chris Lattner6d492922002-08-19 21:32:41 +0000798 abort();
799 }
800}
801
802void CWriter::writeOperandInternal(Value *Operand) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000803 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000804 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000805 // Should we inline this instruction to build a tree?
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000806 Out << '(';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000807 visit(*I);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000808 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000809 return;
810 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000811
Reid Spencer518310c2004-07-18 00:44:37 +0000812 Constant* CPV = dyn_cast<Constant>(Operand);
813 if (CPV && !isa<GlobalValue>(CPV)) {
Misha Brukmand6a29a52005-04-20 16:05:03 +0000814 printConstant(CPV);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000815 } else {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000816 Out << Mang->getValueName(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000817 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000818}
819
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000820void CWriter::writeOperand(Value *Operand) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000821 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000822 Out << "(&"; // Global variables are references as their addresses by llvm
823
824 writeOperandInternal(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000825
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000826 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000827 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000828}
829
Chris Lattner41488192003-06-28 17:15:12 +0000830// generateCompilerSpecificCode - This is where we add conditional compilation
831// directives to cater to specific compilers as need be.
832//
Chris Lattnerc59c1182003-11-16 22:06:14 +0000833static void generateCompilerSpecificCode(std::ostream& Out) {
Chris Lattner9a571ba2006-03-07 22:58:23 +0000834 // Alloca is hard to get, and we don't want to include stdlib.h here.
Chris Lattner41488192003-06-28 17:15:12 +0000835 Out << "/* get a declaration for alloca */\n"
Chris Lattnerd9477602006-06-02 18:54:01 +0000836 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
Reid Spencera8411a62005-01-23 04:32:47 +0000837 << "extern void *_alloca(unsigned long);\n"
838 << "#define alloca(x) _alloca(x)\n"
839 << "#elif defined(__APPLE__)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000840 << "extern void *__builtin_alloca(unsigned long);\n"
841 << "#define alloca(x) __builtin_alloca(x)\n"
Brian Gaekece630052004-12-10 05:44:45 +0000842 << "#elif defined(__sun__)\n"
843 << "#if defined(__sparcv9)\n"
844 << "extern void *__builtin_alloca(unsigned long);\n"
845 << "#else\n"
846 << "extern void *__builtin_alloca(unsigned int);\n"
847 << "#endif\n"
848 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohen3c280bf2006-04-17 17:55:41 +0000849 << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
Chris Lattner60e66742004-10-06 04:21:52 +0000850 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohend01f65a2005-01-06 04:21:49 +0000851 << "#elif !defined(_MSC_VER)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000852 << "#include <alloca.h>\n"
853 << "#endif\n\n";
Chris Lattner41488192003-06-28 17:15:12 +0000854
855 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
856 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner9bda5f52003-06-28 17:53:05 +0000857 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattner41488192003-06-28 17:15:12 +0000858 << "#define __attribute__(X)\n"
Brian Gaeke27f7a712003-12-11 00:24:36 +0000859 << "#endif\n\n";
860
861#if 0
862 // At some point, we should support "external weak" vs. "weak" linkages.
863 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
864 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
865 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
866 << "#elif defined(__GNUC__)\n"
867 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
868 << "#else\n"
869 << "#define __EXTERNAL_WEAK__\n"
870 << "#endif\n\n";
871#endif
872
873 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
874 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
875 << "#define __ATTRIBUTE_WEAK__\n"
876 << "#elif defined(__GNUC__)\n"
877 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
878 << "#else\n"
879 << "#define __ATTRIBUTE_WEAK__\n"
880 << "#endif\n\n";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000881
882 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
883 // From the GCC documentation:
Misha Brukmand6a29a52005-04-20 16:05:03 +0000884 //
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000885 // double __builtin_nan (const char *str)
886 //
887 // This is an implementation of the ISO C99 function nan.
888 //
889 // Since ISO C99 defines this function in terms of strtod, which we do
890 // not implement, a description of the parsing is in order. The string is
891 // parsed as by strtol; that is, the base is recognized by leading 0 or
892 // 0x prefixes. The number parsed is placed in the significand such that
893 // the least significant bit of the number is at the least significant
894 // bit of the significand. The number is truncated to fit the significand
895 // field provided. The significand is forced to be a quiet NaN.
896 //
897 // This function, if given a string literal, is evaluated early enough
898 // that it is considered a compile-time constant.
899 //
900 // float __builtin_nanf (const char *str)
901 //
902 // Similar to __builtin_nan, except the return type is float.
903 //
904 // double __builtin_inf (void)
905 //
906 // Similar to __builtin_huge_val, except a warning is generated if the
907 // target floating-point format does not support infinities. This
908 // function is suitable for implementing the ISO C99 macro INFINITY.
909 //
910 // float __builtin_inff (void)
911 //
912 // Similar to __builtin_inf, except the return type is float.
913 Out << "#ifdef __GNUC__\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +0000914 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
915 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
916 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
917 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
918 << "#define LLVM_INF __builtin_inf() /* Double */\n"
919 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
Chris Lattnerf9a05322006-02-13 22:22:42 +0000920 << "#define LLVM_PREFETCH(addr,rw,locality) "
921 "__builtin_prefetch(addr,rw,locality)\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +0000922 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
923 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +0000924 << "#define LLVM_ASM __asm__\n"
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000925 << "#else\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +0000926 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
927 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
928 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
929 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
930 << "#define LLVM_INF ((double)0.0) /* Double */\n"
931 << "#define LLVM_INFF 0.0F /* Float */\n"
Chris Lattner50a8a172005-05-06 06:58:42 +0000932 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +0000933 << "#define __ATTRIBUTE_CTOR__\n"
934 << "#define __ATTRIBUTE_DTOR__\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +0000935 << "#define LLVM_ASM(X)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +0000936 << "#endif\n\n";
937
938 // Output target-specific code that should be inserted into main.
939 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
940 // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
941 Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
Evan Chenge3db4da2006-06-20 22:11:12 +0000942 << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
943 << "defined(__x86_64__)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +0000944 << "#undef CODE_FOR_MAIN\n"
945 << "#define CODE_FOR_MAIN() \\\n"
946 << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
947 << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
948 << "#endif\n#endif\n";
949
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000950}
951
Chris Lattner9a571ba2006-03-07 22:58:23 +0000952/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
953/// the StaticTors set.
954static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
955 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
956 if (!InitList) return;
957
958 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
959 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
960 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
961
962 if (CS->getOperand(1)->isNullValue())
963 return; // Found a null terminator, exit printing.
964 Constant *FP = CS->getOperand(1);
965 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
966 if (CE->getOpcode() == Instruction::Cast)
967 FP = CE->getOperand(0);
968 if (Function *F = dyn_cast<Function>(FP))
969 StaticTors.insert(F);
970 }
971}
972
973enum SpecialGlobalClass {
974 NotSpecial = 0,
975 GlobalCtors, GlobalDtors,
976 NotPrinted
977};
978
979/// getGlobalVariableClass - If this is a global that is specially recognized
980/// by LLVM, return a code that indicates how we should handle it.
981static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
982 // If this is a global ctors/dtors list, handle it now.
983 if (GV->hasAppendingLinkage() && GV->use_empty()) {
984 if (GV->getName() == "llvm.global_ctors")
985 return GlobalCtors;
986 else if (GV->getName() == "llvm.global_dtors")
987 return GlobalDtors;
988 }
989
990 // Otherwise, it it is other metadata, don't print it. This catches things
991 // like debug information.
992 if (GV->getSection() == "llvm.metadata")
993 return NotPrinted;
994
995 return NotSpecial;
996}
997
998
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000999bool CWriter::doInitialization(Module &M) {
1000 // Initialize
1001 TheModule = &M;
Chris Lattnerc2421432004-05-09 04:30:20 +00001002
1003 IL.AddPrototypes(M);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001004
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001005 // Ensure that all structure types have names...
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001006 Mang = new Mangler(M);
Chris Lattnerba9c6432005-11-10 21:39:29 +00001007 Mang->markCharUnacceptable('.');
Chris Lattnerc59c1182003-11-16 22:06:14 +00001008
Chris Lattner9a571ba2006-03-07 22:58:23 +00001009 // Keep track of which functions are static ctors/dtors so they can have
1010 // an attribute added to their prototypes.
1011 std::set<Function*> StaticCtors, StaticDtors;
1012 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1013 I != E; ++I) {
1014 switch (getGlobalVariableClass(I)) {
1015 default: break;
1016 case GlobalCtors:
1017 FindStaticTors(I, StaticCtors);
1018 break;
1019 case GlobalDtors:
1020 FindStaticTors(I, StaticDtors);
1021 break;
1022 }
1023 }
1024
Chris Lattner16c7bb22002-05-09 02:28:59 +00001025 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001026 Out << "/* Provide Declarations */\n";
Chris Lattnerc59c1182003-11-16 22:06:14 +00001027 Out << "#include <stdarg.h>\n"; // Varargs support
1028 Out << "#include <setjmp.h>\n"; // Unwind support
Chris Lattner41488192003-06-28 17:15:12 +00001029 generateCompilerSpecificCode(Out);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001030
Chris Lattnercf135cb2003-06-02 03:10:53 +00001031 // Provide a definition for `bool' if not compiling with a C++ compiler.
1032 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +00001033 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001034
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001035 << "\n\n/* Support for floating point constants */\n"
1036 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +00001037 << "typedef unsigned int ConstantFloatTy;\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001038
Chris Lattnera4d4a852002-08-19 21:48:40 +00001039 << "\n\n/* Global Declarations */\n";
1040
1041 // First output all the declarations for the program, because C requires
1042 // Functions & globals to be declared before they are used.
1043 //
Chris Lattner16c7bb22002-05-09 02:28:59 +00001044
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001045 // Loop over the symbol table, emitting all named constants...
Chris Lattner68758072004-05-09 06:20:51 +00001046 printModuleTypes(M.getSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001047
Chris Lattnera4d4a852002-08-19 21:48:40 +00001048 // Global variable declarations...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001049 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001050 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001051 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1052 I != E; ++I) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001053 if (I->hasExternalLinkage()) {
1054 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001055 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001056 Out << ";\n";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001057 } else if (I->hasDLLImportLinkage()) {
1058 Out << "__declspec(dllimport) ";
1059 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1060 Out << ";\n";
1061 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001062 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001063 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001064
Chris Lattnera4d4a852002-08-19 21:48:40 +00001065 // Function declarations
Chris Lattner9a571ba2006-03-07 22:58:23 +00001066 Out << "\n/* Function Declarations */\n";
Chris Lattner57da2522005-08-23 20:22:50 +00001067 Out << "double fmod(double, double);\n"; // Support for FP rem
1068 Out << "float fmodf(float, float);\n";
1069
Chris Lattner9a571ba2006-03-07 22:58:23 +00001070 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1071 // Don't print declarations for intrinsic functions.
1072 if (!I->getIntrinsicID() &&
1073 I->getName() != "setjmp" && I->getName() != "longjmp") {
1074 printFunctionSignature(I, true);
1075 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1076 Out << " __ATTRIBUTE_WEAK__";
1077 if (StaticCtors.count(I))
1078 Out << " __ATTRIBUTE_CTOR__";
1079 if (StaticDtors.count(I))
1080 Out << " __ATTRIBUTE_DTOR__";
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001081
1082 if (I->hasName() && I->getName()[0] == 1)
1083 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1084
Chris Lattner9a571ba2006-03-07 22:58:23 +00001085 Out << ";\n";
Chris Lattner4cda8352002-08-20 16:55:48 +00001086 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001087 }
1088
Joel Stanley54f60322003-06-25 04:52:09 +00001089 // Output the global variable declarations
Chris Lattnere4d5c442005-03-15 04:54:21 +00001090 if (!M.global_empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +00001091 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001092 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1093 I != E; ++I)
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001094 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001095 // Ignore special globals, such as debug info.
1096 if (getGlobalVariableClass(I))
1097 continue;
1098
Chris Lattnercc16a8e2004-12-03 17:19:10 +00001099 if (I->hasInternalLinkage())
1100 Out << "static ";
1101 else
1102 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001103 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner2580d4f2003-11-03 17:32:38 +00001104
1105 if (I->hasLinkOnceLinkage())
1106 Out << " __attribute__((common))";
1107 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001108 Out << " __ATTRIBUTE_WEAK__";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001109 Out << ";\n";
1110 }
1111 }
1112
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001113 // Output the global variable definitions and contents...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001114 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001115 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001116 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1117 I != E; ++I)
Chris Lattnere8e035b2002-10-16 20:08:47 +00001118 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001119 // Ignore special globals, such as debug info.
1120 if (getGlobalVariableClass(I))
1121 continue;
1122
Chris Lattnere8e035b2002-10-16 20:08:47 +00001123 if (I->hasInternalLinkage())
1124 Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001125 else if (I->hasDLLImportLinkage())
1126 Out << "__declspec(dllimport) ";
1127 else if (I->hasDLLExportLinkage())
1128 Out << "__declspec(dllexport) ";
1129
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001130 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +00001131 if (I->hasLinkOnceLinkage())
1132 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +00001133 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001134 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner5ea326a2003-11-03 17:35:00 +00001135
1136 // If the initializer is not null, emit the initializer. If it is null,
1137 // we try to avoid emitting large amounts of zeros. The problem with
1138 // this, however, occurs when the variable has weak linkage. In this
1139 // case, the assembler will complain about the variable being both weak
1140 // and common, so we disable this optimization.
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001141 if (!I->getInitializer()->isNullValue()) {
Chris Lattner940b08d2003-06-06 07:10:24 +00001142 Out << " = " ;
1143 writeOperand(I->getInitializer());
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001144 } else if (I->hasWeakLinkage()) {
1145 // We have to specify an initializer, but it doesn't have to be
1146 // complete. If the value is an aggregate, print out { 0 }, and let
1147 // the compiler figure out the rest of the zeros.
1148 Out << " = " ;
1149 if (isa<StructType>(I->getInitializer()->getType()) ||
Robert Bocchinob78e8382006-01-20 20:43:57 +00001150 isa<ArrayType>(I->getInitializer()->getType()) ||
1151 isa<PackedType>(I->getInitializer()->getType())) {
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001152 Out << "{ 0 }";
1153 } else {
1154 // Just print it out normally.
1155 writeOperand(I->getInitializer());
1156 }
Chris Lattner940b08d2003-06-06 07:10:24 +00001157 }
Chris Lattnere8e035b2002-10-16 20:08:47 +00001158 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00001159 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001160 }
1161
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001162 if (!M.empty())
Chris Lattnera4d4a852002-08-19 21:48:40 +00001163 Out << "\n\n/* Function Bodies */\n";
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001164 return false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001165}
1166
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001167
Chris Lattner9860e772003-10-12 04:36:29 +00001168/// Output all floating point constants that cannot be printed accurately...
Chris Lattner68758072004-05-09 06:20:51 +00001169void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner9860e772003-10-12 04:36:29 +00001170 // Scan the module for floating point constants. If any FP constant is used
1171 // in the function, we want to redirect it here so that we do not depend on
1172 // the precision of the printed form, unless the printed form preserves
1173 // precision.
1174 //
Chris Lattner68758072004-05-09 06:20:51 +00001175 static unsigned FPCounter = 0;
1176 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1177 I != E; ++I)
1178 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1179 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1180 !FPConstantMap.count(FPC)) {
1181 double Val = FPC->getValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00001182
Chris Lattner68758072004-05-09 06:20:51 +00001183 FPConstantMap[FPC] = FPCounter; // Number the FP constants
Misha Brukmand6a29a52005-04-20 16:05:03 +00001184
Chris Lattner68758072004-05-09 06:20:51 +00001185 if (FPC->getType() == Type::DoubleTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001186 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001187 << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001188 << "ULL; /* " << Val << " */\n";
1189 } else if (FPC->getType() == Type::FloatTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001190 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001191 << " = 0x" << std::hex << FloatToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001192 << "U; /* " << Val << " */\n";
1193 } else
1194 assert(0 && "Unknown float type!");
1195 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001196
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001197 Out << '\n';
Chris Lattner68758072004-05-09 06:20:51 +00001198}
Chris Lattner9860e772003-10-12 04:36:29 +00001199
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001200
Chris Lattner2db41cd2002-09-20 15:12:13 +00001201/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchinob78e8382006-01-20 20:43:57 +00001202/// type name is found, emit its declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +00001203///
Chris Lattner68758072004-05-09 06:20:51 +00001204void CWriter::printModuleTypes(const SymbolTable &ST) {
Chris Lattnerb15fde22005-03-06 02:28:23 +00001205 // We are only interested in the type plane of the symbol table.
Reid Spencer9231ac82004-05-25 08:53:40 +00001206 SymbolTable::type_const_iterator I = ST.type_begin();
1207 SymbolTable::type_const_iterator End = ST.type_end();
Chris Lattnerb15fde22005-03-06 02:28:23 +00001208
1209 // If there are no type names, exit early.
1210 if (I == End) return;
Misha Brukmand6a29a52005-04-20 16:05:03 +00001211
Chris Lattner58d04d42002-09-20 15:18:30 +00001212 // Print out forward declarations for structure types before anything else!
1213 Out << "/* Structure forward decls */\n";
1214 for (; I != End; ++I)
Chris Lattner68758072004-05-09 06:20:51 +00001215 if (const Type *STy = dyn_cast<StructType>(I->second)) {
Chris Lattner36c975c2005-11-10 18:53:25 +00001216 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001217 Out << Name << ";\n";
1218 TypeNames.insert(std::make_pair(STy, Name));
1219 }
Chris Lattner58d04d42002-09-20 15:18:30 +00001220
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001221 Out << '\n';
Chris Lattner58d04d42002-09-20 15:18:30 +00001222
1223 // Now we can print out typedefs...
1224 Out << "/* Typedefs */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001225 for (I = ST.type_begin(); I != End; ++I) {
Chris Lattner68758072004-05-09 06:20:51 +00001226 const Type *Ty = cast<Type>(I->second);
Chris Lattner36c975c2005-11-10 18:53:25 +00001227 std::string Name = "l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001228 Out << "typedef ";
1229 printType(Out, Ty, Name);
1230 Out << ";\n";
1231 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001232
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001233 Out << '\n';
Chris Lattner3ef6dc72002-05-09 14:40:11 +00001234
Chris Lattner2c601a72002-09-20 15:05:40 +00001235 // Keep track of which structures have been printed so far...
1236 std::set<const StructType *> StructPrinted;
1237
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001238 // Loop over all structures then push them into the stack so they are
1239 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +00001240 //
Chris Lattner58d04d42002-09-20 15:18:30 +00001241 Out << "/* Structure contents */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001242 for (I = ST.type_begin(); I != End; ++I)
Chris Lattner2db41cd2002-09-20 15:12:13 +00001243 if (const StructType *STy = dyn_cast<StructType>(I->second))
Chris Lattnerfa395ec2003-11-02 01:29:27 +00001244 // Only print out used types!
Chris Lattner68758072004-05-09 06:20:51 +00001245 printContainedStructs(STy, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001246}
1247
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001248// Push the struct onto the stack and recursively push all structs
1249// this one depends on.
Robert Bocchinob78e8382006-01-20 20:43:57 +00001250//
1251// TODO: Make this work properly with packed types
1252//
Chris Lattner2c601a72002-09-20 15:05:40 +00001253void CWriter::printContainedStructs(const Type *Ty,
1254 std::set<const StructType*> &StructPrinted){
Chris Lattner14d9b202006-01-20 18:57:03 +00001255 // Don't walk through pointers.
1256 if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1257
1258 // Print all contained types first.
1259 for (Type::subtype_iterator I = Ty->subtype_begin(),
1260 E = Ty->subtype_end(); I != E; ++I)
1261 printContainedStructs(*I, StructPrinted);
1262
Misha Brukmanac25de32003-07-09 17:33:50 +00001263 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner14d9b202006-01-20 18:57:03 +00001264 // Check to see if we have already printed this struct.
1265 if (StructPrinted.insert(STy).second) {
1266 // Print structure type out.
Misha Brukmand6a29a52005-04-20 16:05:03 +00001267 std::string Name = TypeNames[STy];
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001268 printType(Out, STy, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00001269 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001270 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001271 }
1272}
1273
Chris Lattner4cda8352002-08-20 16:55:48 +00001274void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001275 /// isCStructReturn - Should this function actually return a struct by-value?
1276 bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
1277
Joel Stanley54f60322003-06-25 04:52:09 +00001278 if (F->hasInternalLinkage()) Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001279 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1280 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00001281 switch (F->getCallingConv()) {
1282 case CallingConv::X86_StdCall:
1283 Out << "__stdcall ";
1284 break;
1285 case CallingConv::X86_FastCall:
1286 Out << "__fastcall ";
1287 break;
1288 }
1289
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001290 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00001291 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Misha Brukmand6a29a52005-04-20 16:05:03 +00001292
1293 std::stringstream FunctionInnards;
1294
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001295 // Print out the name...
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001296 FunctionInnards << Mang->getValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00001297
Chris Lattner0c54d892006-05-23 23:39:48 +00001298 bool PrintedArg = false;
Chris Lattner16c7bb22002-05-09 02:28:59 +00001299 if (!F->isExternal()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00001300 if (!F->arg_empty()) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001301 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1302
1303 // If this is a struct-return function, don't print the hidden
1304 // struct-return argument.
1305 if (isCStructReturn) {
1306 assert(I != E && "Invalid struct return function!");
1307 ++I;
1308 }
1309
Chris Lattneredd8ce12003-05-03 03:14:35 +00001310 std::string ArgName;
Chris Lattner0c54d892006-05-23 23:39:48 +00001311 for (; I != E; ++I) {
1312 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00001313 if (I->hasName() || !Prototype)
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001314 ArgName = Mang->getValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001315 else
Chris Lattner4cda8352002-08-20 16:55:48 +00001316 ArgName = "";
Joel Stanley54f60322003-06-25 04:52:09 +00001317 printType(FunctionInnards, I->getType(), ArgName);
Chris Lattner0c54d892006-05-23 23:39:48 +00001318 PrintedArg = true;
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001319 }
1320 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001321 } else {
Chris Lattner0c54d892006-05-23 23:39:48 +00001322 // Loop over the arguments, printing them.
1323 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1324
1325 // If this is a struct-return function, don't print the hidden
1326 // struct-return argument.
1327 if (isCStructReturn) {
1328 assert(I != E && "Invalid struct return function!");
1329 ++I;
1330 }
1331
1332 for (; I != E; ++I) {
1333 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001334 printType(FunctionInnards, *I);
Chris Lattner0c54d892006-05-23 23:39:48 +00001335 PrintedArg = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001336 }
1337 }
1338
Chris Lattner1f8c4a12002-09-20 22:32:30 +00001339 // Finish printing arguments... if this is a vararg function, print the ...,
1340 // unless there are no known types, in which case, we just emit ().
1341 //
Chris Lattner0c54d892006-05-23 23:39:48 +00001342 if (FT->isVarArg() && PrintedArg) {
1343 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001344 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattner0c54d892006-05-23 23:39:48 +00001345 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00001346 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001347 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001348 FunctionInnards << ')';
Chris Lattner0c54d892006-05-23 23:39:48 +00001349
1350 // Get the return tpe for the function.
1351 const Type *RetTy;
1352 if (!isCStructReturn)
1353 RetTy = F->getReturnType();
1354 else {
1355 // If this is a struct-return function, print the struct-return type.
1356 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1357 }
1358
1359 // Print out the return type and the signature built above.
1360 printType(Out, RetTy, FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001361}
1362
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001363void CWriter::printFunction(Function &F) {
1364 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001365 Out << " {\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00001366
1367 // If this is a struct return function, handle the result with magic.
1368 if (F.getCallingConv() == CallingConv::CSRet) {
1369 const Type *StructTy =
1370 cast<PointerType>(F.arg_begin()->getType())->getElementType();
1371 Out << " ";
1372 printType(Out, StructTy, "StructReturn");
1373 Out << "; /* Struct return temporary */\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001374
Chris Lattner0c54d892006-05-23 23:39:48 +00001375 Out << " ";
1376 printType(Out, F.arg_begin()->getType(), Mang->getValueName(F.arg_begin()));
1377 Out << " = &StructReturn;\n";
1378 }
1379
1380 bool PrintedVar = false;
1381
Chris Lattner497e19a2002-05-09 20:39:03 +00001382 // print local variable information for the function
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001383 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00001384 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001385 Out << " ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001386 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00001387 Out << "; /* Address-exposed local */\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00001388 PrintedVar = true;
Chris Lattner6ffe5512004-04-27 15:13:33 +00001389 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00001390 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001391 printType(Out, I->getType(), Mang->getValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001392 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001393
Chris Lattner84e66652003-05-03 07:11:00 +00001394 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1395 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001396 printType(Out, I->getType(),
1397 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00001398 Out << ";\n";
1399 }
Chris Lattner0c54d892006-05-23 23:39:48 +00001400 PrintedVar = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001401 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001402
Chris Lattner0c54d892006-05-23 23:39:48 +00001403 if (PrintedVar)
1404 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001405
Chris Lattner395fd592004-12-13 21:52:52 +00001406 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00001407 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00001408
Chris Lattner16c7bb22002-05-09 02:28:59 +00001409 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001410 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001411 if (Loop *L = LI->getLoopFor(BB)) {
1412 if (L->getHeader() == BB && L->getParentLoop() == 0)
1413 printLoop(L);
1414 } else {
1415 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001416 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001417 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001418
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001419 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001420}
1421
Chris Lattnercb3ad012004-05-09 20:41:32 +00001422void CWriter::printLoop(Loop *L) {
1423 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1424 << "' to make GCC happy */\n";
1425 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1426 BasicBlock *BB = L->getBlocks()[i];
1427 Loop *BBLoop = LI->getLoopFor(BB);
1428 if (BBLoop == L)
1429 printBasicBlock(BB);
1430 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00001431 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00001432 }
1433 Out << " } while (1); /* end of syntactic loop '"
1434 << L->getHeader()->getName() << "' */\n";
1435}
1436
1437void CWriter::printBasicBlock(BasicBlock *BB) {
1438
1439 // Don't print the label for the basic block if there are no uses, or if
1440 // the only terminator use is the predecessor basic block's terminator.
1441 // We have to scan the use list because PHI nodes use basic blocks too but
1442 // do not require a label to be generated.
1443 //
1444 bool NeedsLabel = false;
1445 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1446 if (isGotoCodeNecessary(*PI, BB)) {
1447 NeedsLabel = true;
1448 break;
1449 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001450
Chris Lattnercb3ad012004-05-09 20:41:32 +00001451 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001452
Chris Lattnercb3ad012004-05-09 20:41:32 +00001453 // Output all of the instructions in the basic block...
1454 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1455 ++II) {
1456 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1457 if (II->getType() != Type::VoidTy)
1458 outputLValue(II);
1459 else
1460 Out << " ";
1461 visit(*II);
1462 Out << ";\n";
1463 }
1464 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001465
Chris Lattnercb3ad012004-05-09 20:41:32 +00001466 // Don't emit prefix or suffix for the terminator...
1467 visit(*BB->getTerminator());
1468}
1469
1470
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001471// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00001472// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001473//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001474void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001475 // If this is a struct return function, return the temporary struct.
1476 if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
1477 Out << " return StructReturn;\n";
1478 return;
1479 }
1480
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001481 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00001482 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001483 &*--I.getParent()->getParent()->end() == I.getParent() &&
1484 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001485 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00001486 }
Chris Lattner44408262002-05-09 03:50:42 +00001487
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001488 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001489 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001490 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001491 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001492 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001493 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001494}
1495
Chris Lattnera9f5e052003-04-22 20:19:52 +00001496void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001497
Chris Lattnera9f5e052003-04-22 20:19:52 +00001498 Out << " switch (";
1499 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00001500 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00001501 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00001502 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001503 Out << ";\n";
1504 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1505 Out << " case ";
1506 writeOperand(SI.getOperand(i));
1507 Out << ":\n";
1508 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00001509 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001510 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattnerefd02c72005-03-19 17:35:11 +00001511 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00001512 Out << " break;\n";
1513 }
1514 Out << " }\n";
1515}
1516
Chris Lattnera9d12c02004-10-16 18:12:13 +00001517void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00001518 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00001519}
1520
Chris Lattnercb3ad012004-05-09 20:41:32 +00001521bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1522 /// FIXME: This should be reenabled, but loop reordering safe!!
1523 return true;
1524
Chris Lattner67c2d182005-03-18 16:12:37 +00001525 if (next(Function::iterator(From)) != Function::iterator(To))
1526 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00001527
1528 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00001529
Chris Lattnercb3ad012004-05-09 20:41:32 +00001530 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001531 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001532 return false;
1533}
1534
John Criswell57bbfce2004-10-20 14:38:39 +00001535void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00001536 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00001537 unsigned Indent) {
1538 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1539 PHINode *PN = cast<PHINode>(I);
1540 // Now we have to do the printing.
1541 Value *IV = PN->getIncomingValueForBlock(CurBlock);
1542 if (!isa<UndefValue>(IV)) {
1543 Out << std::string(Indent, ' ');
1544 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1545 writeOperand(IV);
1546 Out << "; /* for PHI node */\n";
1547 }
1548 }
1549}
1550
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001551void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00001552 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001553 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00001554 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001555 writeOperand(Succ);
1556 Out << ";\n";
1557 }
1558}
1559
Misha Brukman37f92e22003-09-11 22:34:13 +00001560// Branch instruction printing - Avoid printing out a branch to a basic block
1561// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001562//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001563void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001564
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001565 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001566 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001567 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001568 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001569 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001570
John Criswell57bbfce2004-10-20 14:38:39 +00001571 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001572 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001573
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001574 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001575 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00001576 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001577 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001578 }
1579 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00001580 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001581 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001582 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001583 Out << ") {\n";
1584
John Criswell57bbfce2004-10-20 14:38:39 +00001585 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001586 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001587 }
1588
1589 Out << " }\n";
1590 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00001591 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001592 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001593 }
1594 Out << "\n";
1595}
1596
Chris Lattner84e66652003-05-03 07:11:00 +00001597// PHI nodes get copied into temporary values at the end of predecessor basic
1598// blocks. We now need to copy these temporary values into the REAL value for
1599// the PHI.
1600void CWriter::visitPHINode(PHINode &I) {
1601 writeOperand(&I);
1602 Out << "__PHI_TEMPORARY";
1603}
1604
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001605
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001606void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001607 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00001608 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00001609
1610 // We must cast the results of binary operations which might be promoted.
1611 bool needsCast = false;
1612 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
Brian Gaekee99f4cf2003-06-25 03:05:33 +00001613 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1614 || (I.getType() == Type::FloatTy)) {
Brian Gaeke031a1122003-06-23 20:00:51 +00001615 needsCast = true;
1616 Out << "((";
Chris Lattner7635ea42003-11-03 01:01:59 +00001617 printType(Out, I.getType());
Brian Gaeke031a1122003-06-23 20:00:51 +00001618 Out << ")(";
1619 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001620
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001621 // If this is a negation operation, print it out as such. For FP, we don't
1622 // want to print "-0.0 - X".
1623 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00001624 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001625 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00001626 Out << ")";
Chris Lattner57da2522005-08-23 20:22:50 +00001627 } else if (I.getOpcode() == Instruction::Rem &&
1628 I.getType()->isFloatingPoint()) {
1629 // Output a call to fmod/fmodf instead of emitting a%b
1630 if (I.getType() == Type::FloatTy)
1631 Out << "fmodf(";
1632 else
1633 Out << "fmod(";
1634 writeOperand(I.getOperand(0));
1635 Out << ", ";
1636 writeOperand(I.getOperand(1));
1637 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001638 } else {
1639 writeOperand(I.getOperand(0));
1640
1641 switch (I.getOpcode()) {
1642 case Instruction::Add: Out << " + "; break;
1643 case Instruction::Sub: Out << " - "; break;
1644 case Instruction::Mul: Out << '*'; break;
1645 case Instruction::Div: Out << '/'; break;
1646 case Instruction::Rem: Out << '%'; break;
1647 case Instruction::And: Out << " & "; break;
1648 case Instruction::Or: Out << " | "; break;
1649 case Instruction::Xor: Out << " ^ "; break;
1650 case Instruction::SetEQ: Out << " == "; break;
1651 case Instruction::SetNE: Out << " != "; break;
1652 case Instruction::SetLE: Out << " <= "; break;
1653 case Instruction::SetGE: Out << " >= "; break;
1654 case Instruction::SetLT: Out << " < "; break;
1655 case Instruction::SetGT: Out << " > "; break;
1656 case Instruction::Shl : Out << " << "; break;
1657 case Instruction::Shr : Out << " >> "; break;
1658 default: std::cerr << "Invalid operator type!" << I; abort();
1659 }
1660
1661 writeOperand(I.getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001662 }
1663
Brian Gaeke031a1122003-06-23 20:00:51 +00001664 if (needsCast) {
1665 Out << "))";
1666 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001667}
1668
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001669void CWriter::visitCastInst(CastInst &I) {
Chris Lattnerd13bd222003-06-01 03:36:51 +00001670 if (I.getType() == Type::BoolTy) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001671 Out << '(';
Chris Lattnerd13bd222003-06-01 03:36:51 +00001672 writeOperand(I.getOperand(0));
1673 Out << " != 0)";
1674 return;
1675 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001676 Out << '(';
Chris Lattner7635ea42003-11-03 01:01:59 +00001677 printType(Out, I.getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001678 Out << ')';
Chris Lattnerf5612b762003-04-23 19:09:22 +00001679 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1680 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1681 // Avoid "cast to pointer from integer of different size" warnings
Misha Brukmand6a29a52005-04-20 16:05:03 +00001682 Out << "(long)";
Chris Lattnerf5612b762003-04-23 19:09:22 +00001683 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001684
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001685 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001686}
1687
Chris Lattner9f24a072004-03-12 05:52:14 +00001688void CWriter::visitSelectInst(SelectInst &I) {
1689 Out << "((";
1690 writeOperand(I.getCondition());
1691 Out << ") ? (";
1692 writeOperand(I.getTrueValue());
1693 Out << ") : (";
1694 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00001695 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00001696}
1697
1698
Chris Lattnerc2421432004-05-09 04:30:20 +00001699void CWriter::lowerIntrinsics(Function &F) {
1700 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1701 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1702 if (CallInst *CI = dyn_cast<CallInst>(I++))
1703 if (Function *F = CI->getCalledFunction())
1704 switch (F->getIntrinsicID()) {
1705 case Intrinsic::not_intrinsic:
1706 case Intrinsic::vastart:
1707 case Intrinsic::vacopy:
1708 case Intrinsic::vaend:
1709 case Intrinsic::returnaddress:
1710 case Intrinsic::frameaddress:
1711 case Intrinsic::setjmp:
1712 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00001713 case Intrinsic::prefetch:
Jim Laskey7075d6f2006-03-08 19:31:15 +00001714 case Intrinsic::dbg_stoppoint:
Chris Lattner1e142892006-09-09 06:17:12 +00001715 case Intrinsic::powi_f32:
1716 case Intrinsic::powi_f64:
Chris Lattnerc2421432004-05-09 04:30:20 +00001717 // We directly implement these intrinsics
1718 break;
1719 default:
Chris Lattner87242152006-03-13 23:09:05 +00001720 // If this is an intrinsic that directly corresponds to a GCC
1721 // builtin, we handle it.
1722 const char *BuiltinName = "";
1723#define GET_GCC_BUILTIN_NAME
1724#include "llvm/Intrinsics.gen"
1725#undef GET_GCC_BUILTIN_NAME
1726 // If we handle it, don't lower it.
1727 if (BuiltinName[0]) break;
1728
Chris Lattnerc2421432004-05-09 04:30:20 +00001729 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00001730 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00001731 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00001732 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00001733
Chris Lattnerc2421432004-05-09 04:30:20 +00001734 IL.LowerIntrinsicCall(CI);
1735 if (Before) { // Move iterator to instruction after call
1736 I = Before; ++I;
1737 } else {
1738 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00001739 }
Chris Lattner87242152006-03-13 23:09:05 +00001740 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00001741 }
Chris Lattner4ef51372004-02-14 00:31:10 +00001742}
1743
1744
1745
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001746void CWriter::visitCallInst(CallInst &I) {
Chris Lattner87242152006-03-13 23:09:05 +00001747 bool WroteCallee = false;
1748
Chris Lattner18ac3c82003-05-08 18:41:45 +00001749 // Handle intrinsic function calls first...
1750 if (Function *F = I.getCalledFunction())
Brian Gaeked0fde302003-11-11 22:41:34 +00001751 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattner18ac3c82003-05-08 18:41:45 +00001752 switch (ID) {
Chris Lattner87242152006-03-13 23:09:05 +00001753 default: {
1754 // If this is an intrinsic that directly corresponds to a GCC
1755 // builtin, we emit it here.
1756 const char *BuiltinName = "";
1757#define GET_GCC_BUILTIN_NAME
1758#include "llvm/Intrinsics.gen"
1759#undef GET_GCC_BUILTIN_NAME
1760 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
1761
1762 Out << BuiltinName;
1763 WroteCallee = true;
1764 break;
1765 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001766 case Intrinsic::vastart:
Chris Lattner4d45bd02003-10-18 05:57:43 +00001767 Out << "0; ";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001768
Andrew Lenharth558bc882005-06-18 18:34:52 +00001769 Out << "va_start(*(va_list*)";
1770 writeOperand(I.getOperand(1));
1771 Out << ", ";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001772 // Output the last argument to the enclosing function...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001773 if (I.getParent()->getParent()->arg_empty()) {
Chris Lattner4065ef92003-10-23 18:39:22 +00001774 std::cerr << "The C backend does not currently support zero "
1775 << "argument varargs functions, such as '"
1776 << I.getParent()->getParent()->getName() << "'!\n";
1777 abort();
1778 }
Chris Lattnerc5e7df12005-03-15 04:59:17 +00001779 writeOperand(--I.getParent()->getParent()->arg_end());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001780 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00001781 return;
Chris Lattner317201d2004-03-13 00:24:00 +00001782 case Intrinsic::vaend:
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00001783 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00001784 Out << "0; va_end(*(va_list*)";
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00001785 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001786 Out << ')';
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00001787 } else {
1788 Out << "va_end(*(va_list*)0)";
1789 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00001790 return;
Chris Lattner317201d2004-03-13 00:24:00 +00001791 case Intrinsic::vacopy:
Andrew Lenharth558bc882005-06-18 18:34:52 +00001792 Out << "0; ";
1793 Out << "va_copy(*(va_list*)";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001794 writeOperand(I.getOperand(1));
Andrew Lenharth213e5572005-06-22 21:04:42 +00001795 Out << ", *(va_list*)";
Andrew Lenharth558bc882005-06-18 18:34:52 +00001796 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001797 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00001798 return;
Chris Lattnerfe1554a2004-02-14 02:55:36 +00001799 case Intrinsic::returnaddress:
1800 Out << "__builtin_return_address(";
1801 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001802 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00001803 return;
1804 case Intrinsic::frameaddress:
1805 Out << "__builtin_frame_address(";
1806 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001807 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00001808 return;
Chris Lattner1e142892006-09-09 06:17:12 +00001809 case Intrinsic::powi_f32:
1810 case Intrinsic::powi_f64:
1811 Out << "__builtin_powi(";
1812 writeOperand(I.getOperand(1));
1813 Out << ", ";
1814 writeOperand(I.getOperand(2));
1815 Out << ')';
1816 return;
Chris Lattnere42cde22004-02-15 22:51:47 +00001817 case Intrinsic::setjmp:
Chris Lattner475c5532006-06-06 21:45:47 +00001818#if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
1819 Out << "_"; // Use _setjmp on systems that support it!
1820#endif
Chris Lattnere42cde22004-02-15 22:51:47 +00001821 Out << "setjmp(*(jmp_buf*)";
1822 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001823 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00001824 return;
1825 case Intrinsic::longjmp:
Chris Lattner475c5532006-06-06 21:45:47 +00001826#if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
1827 Out << "_"; // Use _longjmp on systems that support it!
1828#endif
Chris Lattnere42cde22004-02-15 22:51:47 +00001829 Out << "longjmp(*(jmp_buf*)";
1830 writeOperand(I.getOperand(1));
1831 Out << ", ";
1832 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001833 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00001834 return;
Chris Lattner33e9d292005-02-28 19:29:46 +00001835 case Intrinsic::prefetch:
Chris Lattnerca76f352005-02-28 19:36:15 +00001836 Out << "LLVM_PREFETCH((const void *)";
Chris Lattner33e9d292005-02-28 19:29:46 +00001837 writeOperand(I.getOperand(1));
1838 Out << ", ";
1839 writeOperand(I.getOperand(2));
1840 Out << ", ";
1841 writeOperand(I.getOperand(3));
1842 Out << ")";
Chris Lattnerca76f352005-02-28 19:36:15 +00001843 return;
Jim Laskey7075d6f2006-03-08 19:31:15 +00001844 case Intrinsic::dbg_stoppoint: {
1845 // If we use writeOperand directly we get a "u" suffix which is rejected
1846 // by gcc.
Jim Laskey580418e2006-03-23 18:08:29 +00001847 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey7075d6f2006-03-08 19:31:15 +00001848
1849 Out << "\n#line "
Jim Laskey580418e2006-03-23 18:08:29 +00001850 << SPI.getLine()
1851 << " \"" << SPI.getDirectory()
1852 << SPI.getFileName() << "\"\n";
Jim Laskey7075d6f2006-03-08 19:31:15 +00001853 return;
1854 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00001855 }
1856 }
1857
Chris Lattner4394d512004-11-13 22:21:56 +00001858 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00001859
Chris Lattner0c54d892006-05-23 23:39:48 +00001860 // If this is a call to a struct-return function, assign to the first
1861 // parameter instead of passing it to the call.
1862 bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
1863 if (isStructRet) {
1864 Out << "*(";
1865 writeOperand(I.getOperand(1));
1866 Out << ") = ";
1867 }
1868
Chris Lattnerfe673d92005-05-06 06:53:07 +00001869 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattner4394d512004-11-13 22:21:56 +00001870
1871 const PointerType *PTy = cast<PointerType>(Callee->getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001872 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner0c54d892006-05-23 23:39:48 +00001873
1874 if (!WroteCallee) {
1875 // If this is an indirect call to a struct return function, we need to cast
1876 // the pointer.
1877 bool NeedsCast = isStructRet && !isa<Function>(Callee);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001878
Chris Lattner0c54d892006-05-23 23:39:48 +00001879 // GCC is a real PITA. It does not permit codegening casts of functions to
1880 // function pointers if they are in a call (it generates a trap instruction
1881 // instead!). We work around this by inserting a cast to void* in between
1882 // the function and the function pointer cast. Unfortunately, we can't just
1883 // form the constant expression here, because the folder will immediately
1884 // nuke it.
1885 //
1886 // Note finally, that this is completely unsafe. ANSI C does not guarantee
1887 // that void* and function pointers have the same size. :( To deal with this
1888 // in the common case, we handle casts where the number of arguments passed
1889 // match exactly.
1890 //
1891 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
1892 if (CE->getOpcode() == Instruction::Cast)
1893 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
1894 NeedsCast = true;
1895 Callee = RF;
1896 }
1897
1898 if (NeedsCast) {
1899 // Ok, just cast the pointer type.
1900 Out << "((";
1901 if (!isStructRet)
1902 printType(Out, I.getCalledValue()->getType());
1903 else
1904 printStructReturnPointerFunctionType(Out,
1905 cast<PointerType>(I.getCalledValue()->getType()));
1906 Out << ")(void*)";
1907 }
1908 writeOperand(Callee);
1909 if (NeedsCast) Out << ')';
1910 }
1911
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001912 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001913
Chris Lattner4394d512004-11-13 22:21:56 +00001914 unsigned NumDeclaredParams = FTy->getNumParams();
1915
Chris Lattner0c54d892006-05-23 23:39:48 +00001916 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
1917 unsigned ArgNo = 0;
1918 if (isStructRet) { // Skip struct return argument.
1919 ++AI;
1920 ++ArgNo;
1921 }
1922
1923 bool PrintedArg = false;
1924 for (; AI != AE; ++AI, ++ArgNo) {
1925 if (PrintedArg) Out << ", ";
1926 if (ArgNo < NumDeclaredParams &&
1927 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001928 Out << '(';
Chris Lattner0c54d892006-05-23 23:39:48 +00001929 printType(Out, FTy->getParamType(ArgNo));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001930 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00001931 }
Chris Lattner9bda5f52003-06-28 17:53:05 +00001932 writeOperand(*AI);
Chris Lattner0c54d892006-05-23 23:39:48 +00001933 PrintedArg = true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001934 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001935 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00001936}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001937
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001938void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00001939 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001940}
1941
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001942void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001943 Out << '(';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001944 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001945 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001946 printType(Out, I.getType()->getElementType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001947 Out << ')';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001948 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001949 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001950 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001951 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001952 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001953}
1954
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001955void CWriter::visitFreeInst(FreeInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00001956 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001957}
1958
Chris Lattner23e90702003-11-25 20:49:55 +00001959void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1960 gep_type_iterator E) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001961 bool HasImplicitAddress = false;
1962 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1963 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1964 HasImplicitAddress = true;
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001965 } else if (isDirectAlloca(Ptr)) {
1966 HasImplicitAddress = true;
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001967 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001968
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001969 if (I == E) {
1970 if (!HasImplicitAddress)
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001971 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001972
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001973 writeOperandInternal(Ptr);
1974 return;
1975 }
1976
Chris Lattner23e90702003-11-25 20:49:55 +00001977 const Constant *CI = dyn_cast<Constant>(I.getOperand());
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001978 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1979 Out << "(&";
1980
1981 writeOperandInternal(Ptr);
1982
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001983 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001984 Out << ')';
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001985 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1986 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001987
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001988 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1989 "Can only have implicit address with direct accessing");
1990
1991 if (HasImplicitAddress) {
1992 ++I;
Chris Lattner23e90702003-11-25 20:49:55 +00001993 } else if (CI && CI->isNullValue()) {
1994 gep_type_iterator TmpI = I; ++TmpI;
1995
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001996 // Print out the -> operator if possible...
Chris Lattner23e90702003-11-25 20:49:55 +00001997 if (TmpI != E && isa<StructType>(*TmpI)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001998 Out << (HasImplicitAddress ? "." : "->");
Chris Lattnerbc771c52003-11-25 23:44:40 +00001999 Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
Chris Lattner23e90702003-11-25 20:49:55 +00002000 I = ++TmpI;
2001 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002002 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00002003
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002004 for (; I != E; ++I)
Chris Lattner23e90702003-11-25 20:49:55 +00002005 if (isa<StructType>(*I)) {
2006 Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002007 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002008 Out << '[';
Chris Lattner23e90702003-11-25 20:49:55 +00002009 writeOperand(I.getOperand());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002010 Out << ']';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002011 }
2012}
2013
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002014void CWriter::visitLoadInst(LoadInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002015 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00002016 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00002017 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00002018 printType(Out, I.getType(), "volatile*");
2019 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00002020 }
2021
Chris Lattner5dfe7672002-08-22 22:48:55 +00002022 writeOperand(I.getOperand(0));
Chris Lattner9d30e222005-02-14 16:47:52 +00002023
2024 if (I.isVolatile())
Misha Brukman23ba0c52005-03-08 00:26:08 +00002025 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002026}
2027
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002028void CWriter::visitStoreInst(StoreInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002029 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00002030 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00002031 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00002032 printType(Out, I.getOperand(0)->getType(), " volatile*");
2033 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00002034 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00002035 writeOperand(I.getPointerOperand());
Misha Brukman23ba0c52005-03-08 00:26:08 +00002036 if (I.isVolatile()) Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002037 Out << " = ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002038 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002039}
2040
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002041void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002042 Out << '&';
Chris Lattner23e90702003-11-25 20:49:55 +00002043 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2044 gep_type_end(I));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002045}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002046
Chris Lattner4d45bd02003-10-18 05:57:43 +00002047void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00002048 Out << "va_arg(*(va_list*)";
Chris Lattner4d45bd02003-10-18 05:57:43 +00002049 writeOperand(I.getOperand(0));
Andrew Lenharth558bc882005-06-18 18:34:52 +00002050 Out << ", ";
Chris Lattner7635ea42003-11-03 01:01:59 +00002051 printType(Out, I.getType());
Andrew Lenharth558bc882005-06-18 18:34:52 +00002052 Out << ");\n ";
Chris Lattner4d45bd02003-10-18 05:57:43 +00002053}
2054
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002055//===----------------------------------------------------------------------===//
2056// External Interface declaration
2057//===----------------------------------------------------------------------===//
2058
Chris Lattner1911fd42006-09-04 04:14:57 +00002059bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2060 std::ostream &o,
2061 CodeGenFileType FileType,
2062 bool Fast) {
Chris Lattner0431c962005-06-25 02:48:37 +00002063 if (FileType != TargetMachine::AssemblyFile) return true;
2064
Chris Lattner99c59e82004-05-23 21:23:35 +00002065 PM.add(createLowerGCPass());
Chris Lattnerf7fe4942005-03-03 01:04:50 +00002066 PM.add(createLowerAllocationsPass(true));
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002067 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00002068 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00002069 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00002070 PM.add(new CWriter(o));
Chris Lattnerf31182a2004-02-13 23:18:48 +00002071 return false;
2072}