blob: ff95e90dc72ff728ff9438f514d6674913eab88d [file] [log] [blame]
Reid Spencer69fb8612007-01-10 04:17:32 +00001//===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
Misha Brukmanea548c02005-04-20 16:05:03 +00002//
John Criswell482202a2003-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 Brukmanea548c02005-04-20 16:05:03 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00009//
Chris Lattner337df9b2004-02-13 06:18:21 +000010// This library converts LLVM code to C code, compilable by GCC and other C
11// compilers.
Chris Lattnereabc6472002-05-09 02:28:59 +000012//
Chris Lattner57ebe402003-05-03 03:14:35 +000013//===----------------------------------------------------------------------===//
Chris Lattner5b5c7932003-05-03 07:11:00 +000014
Chris Lattner0591bb52004-02-13 23:18:48 +000015#include "CTargetMachine.h"
Chris Lattnerde177e02006-05-23 23:39:48 +000016#include "llvm/CallingConv.h"
Sumant Kowshikcf3afd92002-05-08 18:09:58 +000017#include "llvm/Constants.h"
Chris Lattner7fbd8312002-05-09 03:28:37 +000018#include "llvm/DerivedTypes.h"
19#include "llvm/Module.h"
Chris Lattnerf86060f2003-04-22 20:19:52 +000020#include "llvm/Instructions.h"
Reid Spencer71b79e32007-04-09 06:17:21 +000021#include "llvm/ParameterAttributes.h"
Chris Lattnerc61f6b02002-08-31 00:29:16 +000022#include "llvm/Pass.h"
Chris Lattnerd2b6e182004-02-13 23:00:29 +000023#include "llvm/PassManager.h"
Reid Spencer32af9e82007-01-06 07:24:44 +000024#include "llvm/TypeSymbolTable.h"
Chris Lattner7ba4f0a2003-05-08 18:41:45 +000025#include "llvm/Intrinsics.h"
Jim Laskey267d39d2006-03-23 18:08:29 +000026#include "llvm/IntrinsicInst.h"
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +000027#include "llvm/InlineAsm.h"
Chris Lattner230d8322002-09-20 23:26:33 +000028#include "llvm/Analysis/ConstantsScanner.h"
Chris Lattnerf719a522004-05-09 20:41:32 +000029#include "llvm/Analysis/FindUsedTypes.h"
30#include "llvm/Analysis/LoopInfo.h"
Chris Lattnerbcdadf32004-06-20 07:49:54 +000031#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattnerd2b6e182004-02-13 23:00:29 +000032#include "llvm/Transforms/Scalar.h"
Chris Lattner4266f802004-07-11 02:48:49 +000033#include "llvm/Target/TargetMachineRegistry.h"
Andrew Lenharth212f15f2006-11-28 19:53:36 +000034#include "llvm/Target/TargetAsmInfo.h"
Reid Spencer1e960cd2007-01-29 17:51:02 +000035#include "llvm/Target/TargetData.h"
Chris Lattner637ee392003-11-25 20:49:55 +000036#include "llvm/Support/CallSite.h"
Chris Lattner2484a632004-05-09 03:42:48 +000037#include "llvm/Support/CFG.h"
Chris Lattner637ee392003-11-25 20:49:55 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Sumant Kowshikcf3afd92002-05-08 18:09:58 +000039#include "llvm/Support/InstVisitor.h"
Brian Gaeke3d35fad2003-07-25 20:21:06 +000040#include "llvm/Support/Mangler.h"
Jim Laskeyb74c6662005-08-17 19:34:49 +000041#include "llvm/Support/MathExtras.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000042#include "llvm/ADT/StringExtras.h"
Chris Lattnerbed96572005-03-18 16:12:37 +000043#include "llvm/ADT/STLExtras.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000044#include "llvm/Support/MathExtras.h"
45#include "llvm/Config/config.h"
Sumant Kowshikcf3afd92002-05-08 18:09:58 +000046#include <algorithm>
Bill Wendling30c0f332006-12-07 23:41:45 +000047#include <sstream>
Chris Lattner337df9b2004-02-13 06:18:21 +000048using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000049
Sumant Kowshikcf3afd92002-05-08 18:09:58 +000050namespace {
Chris Lattner4266f802004-07-11 02:48:49 +000051 // Register the target.
Chris Lattner73eb9432004-07-11 03:27:42 +000052 RegisterTarget<CTargetMachine> X("c", " C backend");
Chris Lattner4266f802004-07-11 02:48:49 +000053
Chris Lattnerd2d174d2006-02-13 22:22:42 +000054 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
55 /// any unnamed structure types that are used by the program, and merges
56 /// external functions with the same name.
Chris Lattner9c299912004-05-09 06:20:51 +000057 ///
Chris Lattnerd2d174d2006-02-13 22:22:42 +000058 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
Devang Patel09f162c2007-05-01 21:15:47 +000059 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000060 static char ID;
Devang Patel09f162c2007-05-01 21:15:47 +000061 CBackendNameAllUsedStructsAndMergeFunctions()
62 : ModulePass((intptr_t)&ID) {}
Chris Lattner9c299912004-05-09 06:20:51 +000063 void getAnalysisUsage(AnalysisUsage &AU) const {
64 AU.addRequired<FindUsedTypes>();
65 }
66
67 virtual const char *getPassName() const {
68 return "C backend type canonicalizer";
69 }
70
Chris Lattner4f2cf032004-09-20 04:48:05 +000071 virtual bool runOnModule(Module &M);
Chris Lattner9c299912004-05-09 06:20:51 +000072 };
Misha Brukmanea548c02005-04-20 16:05:03 +000073
Devang Patel8c78a0b2007-05-03 01:11:54 +000074 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
Devang Patel09f162c2007-05-01 21:15:47 +000075
Chris Lattner9c299912004-05-09 06:20:51 +000076 /// CWriter - This class is the main chunk of code that converts an LLVM
77 /// module to a C translation unit.
78 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
Misha Brukmanea548c02005-04-20 16:05:03 +000079 std::ostream &Out;
Reid Spencer1e960cd2007-01-29 17:51:02 +000080 IntrinsicLowering *IL;
Brian Gaeke46f8b712003-07-24 20:20:44 +000081 Mangler *Mang;
Chris Lattnerf719a522004-05-09 20:41:32 +000082 LoopInfo *LI;
Sumant Kowshikcf3afd92002-05-08 18:09:58 +000083 const Module *TheModule;
Andrew Lenharth212f15f2006-11-28 19:53:36 +000084 const TargetAsmInfo* TAsm;
Reid Spencer1e960cd2007-01-29 17:51:02 +000085 const TargetData* TD;
Chris Lattner57ebe402003-05-03 03:14:35 +000086 std::map<const Type *, std::string> TypeNames;
Chris Lattner57ebe402003-05-03 03:14:35 +000087 std::map<const ConstantFP *, unsigned> FPConstantMap;
Reid Spencer0ef2ca82007-04-12 21:00:45 +000088 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
89
Sumant Kowshikcf3afd92002-05-08 18:09:58 +000090 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000091 static char ID;
Devang Patel09f162c2007-05-01 21:15:47 +000092 CWriter(std::ostream &o)
93 : FunctionPass((intptr_t)&ID), Out(o), IL(0), Mang(0), LI(0),
94 TheModule(0), TAsm(0), TD(0) {}
Chris Lattnerc61f6b02002-08-31 00:29:16 +000095
Chris Lattnerd2b6e182004-02-13 23:00:29 +000096 virtual const char *getPassName() const { return "C backend"; }
Chris Lattnerc61f6b02002-08-31 00:29:16 +000097
Chris Lattnerf719a522004-05-09 20:41:32 +000098 void getAnalysisUsage(AnalysisUsage &AU) const {
99 AU.addRequired<LoopInfo>();
100 AU.setPreservesAll();
101 }
102
Chris Lattner9c299912004-05-09 06:20:51 +0000103 virtual bool doInitialization(Module &M);
Chris Lattnerc61f6b02002-08-31 00:29:16 +0000104
Chris Lattner9c299912004-05-09 06:20:51 +0000105 bool runOnFunction(Function &F) {
Chris Lattnerf719a522004-05-09 20:41:32 +0000106 LI = &getAnalysis<LoopInfo>();
107
Chris Lattnerf878f752004-12-05 06:49:44 +0000108 // Get rid of intrinsics we can't handle.
109 lowerIntrinsics(F);
110
Chris Lattner9c299912004-05-09 06:20:51 +0000111 // Output all floating point constants that cannot be printed accurately.
112 printFloatingPointConstants(F);
Chris Lattnerf878f752004-12-05 06:49:44 +0000113
Chris Lattner9c299912004-05-09 06:20:51 +0000114 printFunction(F);
115 FPConstantMap.clear();
116 return false;
117 }
Chris Lattnerc61f6b02002-08-31 00:29:16 +0000118
Chris Lattner9c299912004-05-09 06:20:51 +0000119 virtual bool doFinalization(Module &M) {
Chris Lattnerc61f6b02002-08-31 00:29:16 +0000120 // Free memory...
Brian Gaeke46f8b712003-07-24 20:20:44 +0000121 delete Mang;
Chris Lattnerc61f6b02002-08-31 00:29:16 +0000122 TypeNames.clear();
Chris Lattnerf719a522004-05-09 20:41:32 +0000123 return false;
Chris Lattnerc61f6b02002-08-31 00:29:16 +0000124 }
Sumant Kowshikcf3afd92002-05-08 18:09:58 +0000125
Reid Spencerdf7c61d2007-01-07 03:24:48 +0000126 std::ostream &printType(std::ostream &Out, const Type *Ty,
Reid Spencer1fc9be32007-01-09 17:09:09 +0000127 bool isSigned = false,
Chris Lattner57ebe402003-05-03 03:14:35 +0000128 const std::string &VariableName = "",
Chris Lattner7af7d942003-11-03 01:01:59 +0000129 bool IgnoreName = false);
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000130 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
Reid Spencer266e42b2006-12-23 06:05:41 +0000131 bool isSigned,
132 const std::string &NameSoFar = "");
Sumant Kowshikcf3afd92002-05-08 18:09:58 +0000133
Chris Lattnerde177e02006-05-23 23:39:48 +0000134 void printStructReturnPointerFunctionType(std::ostream &Out,
135 const PointerType *Ty);
136
Chris Lattnerf8b06682002-06-25 15:57:03 +0000137 void writeOperand(Value *Operand);
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +0000138 void writeOperandRaw(Value *Operand);
Chris Lattnerf8b06682002-06-25 15:57:03 +0000139 void writeOperandInternal(Value *Operand);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000140 void writeOperandWithCast(Value* Operand, unsigned Opcode);
Reid Spencer266e42b2006-12-23 06:05:41 +0000141 void writeOperandWithCast(Value* Operand, ICmpInst::Predicate predicate);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000142 bool writeInstructionCast(const Instruction &I);
Chris Lattner234ad492002-05-09 03:06:06 +0000143
Chris Lattner5d190e22002-05-09 20:53:56 +0000144 private :
Andrew Lenharth212f15f2006-11-28 19:53:36 +0000145 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
146
Chris Lattner14d328e2004-05-09 04:30:20 +0000147 void lowerIntrinsics(Function &F);
Chris Lattner0997f202004-02-14 00:31:10 +0000148
Chris Lattner4933e7e2002-05-09 15:49:41 +0000149 void printModule(Module *M);
Reid Spencer32af9e82007-01-06 07:24:44 +0000150 void printModuleTypes(const TypeSymbolTable &ST);
Chris Lattner9a973b42002-09-20 15:05:40 +0000151 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
Chris Lattner9c299912004-05-09 06:20:51 +0000152 void printFloatingPointConstants(Function &F);
Chris Lattner7934dad2002-08-20 16:55:48 +0000153 void printFunctionSignature(const Function *F, bool Prototype);
154
Chris Lattnerd2b6e182004-02-13 23:00:29 +0000155 void printFunction(Function &);
Chris Lattnerf719a522004-05-09 20:41:32 +0000156 void printBasicBlock(BasicBlock *BB);
157 void printLoop(Loop *L);
Chris Lattner234ad492002-05-09 03:06:06 +0000158
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000159 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
Chris Lattnerfda3b292002-08-19 21:32:41 +0000160 void printConstant(Constant *CPV);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000161 void printConstantWithCast(Constant *CPV, unsigned Opcode);
162 bool printConstExprCast(const ConstantExpr *CE);
Chris Lattnerfda3b292002-08-19 21:32:41 +0000163 void printConstantArray(ConstantArray *CPA);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000164 void printConstantVector(ConstantVector *CP);
Chris Lattnerfda3b292002-08-19 21:32:41 +0000165
Chris Lattnerd4c569c2002-05-09 21:18:38 +0000166 // isInlinableInst - Attempt to inline instructions into their uses to build
167 // trees as much as possible. To do this, we have to consistently decide
168 // what is acceptable to inline, so that variable declarations don't get
169 // printed and an extra copy of the expr is not emitted.
170 //
Chris Lattnerf8b06682002-06-25 15:57:03 +0000171 static bool isInlinableInst(const Instruction &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000172 // Always inline cmp instructions, even if they are shared by multiple
Chris Lattner83c139d2004-05-20 20:25:50 +0000173 // expressions. GCC generates horrible code if we don't.
Reid Spencer266e42b2006-12-23 06:05:41 +0000174 if (isa<CmpInst>(I))
175 return true;
Chris Lattner83c139d2004-05-20 20:25:50 +0000176
Chris Lattnerd4c569c2002-05-09 21:18:38 +0000177 // Must be an expression, must be used exactly once. If it is dead, we
178 // emit it inline where it would go.
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000179 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
Misha Brukmanea548c02005-04-20 16:05:03 +0000180 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Andrew Lenharth9144ec42005-06-18 18:34:52 +0000181 isa<LoadInst>(I) || isa<VAArgInst>(I))
Chris Lattnerbbc2bc12003-07-23 20:45:31 +0000182 // Don't inline a load across a store or other bad things!
Chris Lattnerd4c569c2002-05-09 21:18:38 +0000183 return false;
184
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +0000185 // Must not be used in inline asm
186 if (I.hasOneUse() && isInlineAsm(*I.use_back())) return false;
187
Reid Spencerb9435552006-12-11 20:39:15 +0000188 // Only inline instruction it if it's use is in the same BB as the inst.
Chris Lattnerf8b06682002-06-25 15:57:03 +0000189 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd4c569c2002-05-09 21:18:38 +0000190 }
191
Chris Lattnerfb70cf52003-06-17 04:39:14 +0000192 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
193 // variables which are accessed with the & operator. This causes GCC to
194 // generate significantly better code than to emit alloca calls directly.
195 //
196 static const AllocaInst *isDirectAlloca(const Value *V) {
197 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
198 if (!AI) return false;
199 if (AI->isArrayAllocation())
200 return 0; // FIXME: we can also inline fixed size array allocas!
Chris Lattner5dac64f2003-09-20 14:39:18 +0000201 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
Chris Lattnerfb70cf52003-06-17 04:39:14 +0000202 return 0;
203 return AI;
204 }
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +0000205
206 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
207 static bool isInlineAsm(const Instruction& I) {
208 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
209 return true;
210 return false;
211 }
212
Chris Lattner5d190e22002-05-09 20:53:56 +0000213 // Instruction visitation functions
214 friend class InstVisitor<CWriter>;
Sumant Kowshikcf3afd92002-05-08 18:09:58 +0000215
Chris Lattnerf8b06682002-06-25 15:57:03 +0000216 void visitReturnInst(ReturnInst &I);
217 void visitBranchInst(BranchInst &I);
Chris Lattnerf86060f2003-04-22 20:19:52 +0000218 void visitSwitchInst(SwitchInst &I);
Chris Lattnerf719a522004-05-09 20:41:32 +0000219 void visitInvokeInst(InvokeInst &I) {
220 assert(0 && "Lowerinvoke pass didn't work!");
221 }
222
223 void visitUnwindInst(UnwindInst &I) {
224 assert(0 && "Lowerinvoke pass didn't work!");
225 }
Chris Lattner583dfdc2004-10-16 18:12:13 +0000226 void visitUnreachableInst(UnreachableInst &I);
Sumant Kowshikcf3afd92002-05-08 18:09:58 +0000227
Chris Lattner5b5c7932003-05-03 07:11:00 +0000228 void visitPHINode(PHINode &I);
Chris Lattnerf8b06682002-06-25 15:57:03 +0000229 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000230 void visitICmpInst(ICmpInst &I);
231 void visitFCmpInst(FCmpInst &I);
Sumant Kowshikcf3afd92002-05-08 18:09:58 +0000232
Chris Lattnerf8b06682002-06-25 15:57:03 +0000233 void visitCastInst (CastInst &I);
Chris Lattner65a64e12004-03-12 05:52:14 +0000234 void visitSelectInst(SelectInst &I);
Chris Lattnerf8b06682002-06-25 15:57:03 +0000235 void visitCallInst (CallInst &I);
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +0000236 void visitInlineAsm(CallInst &I);
Chris Lattner5d190e22002-05-09 20:53:56 +0000237
Chris Lattnerf8b06682002-06-25 15:57:03 +0000238 void visitMallocInst(MallocInst &I);
239 void visitAllocaInst(AllocaInst &I);
240 void visitFreeInst (FreeInst &I);
241 void visitLoadInst (LoadInst &I);
242 void visitStoreInst (StoreInst &I);
243 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner5b337482003-10-18 05:57:43 +0000244 void visitVAArgInst (VAArgInst &I);
Chris Lattner7fbd8312002-05-09 03:28:37 +0000245
Chris Lattnerf8b06682002-06-25 15:57:03 +0000246 void visitInstruction(Instruction &I) {
Bill Wendling9bfb1e12006-12-07 22:21:48 +0000247 cerr << "C Writer does not know about " << I;
Chris Lattner5d190e22002-05-09 20:53:56 +0000248 abort();
249 }
250
251 void outputLValue(Instruction *I) {
Bill Wendling77a345f2007-02-23 22:45:08 +0000252 Out << " " << GetValueName(I) << " = ";
Chris Lattner5d190e22002-05-09 20:53:56 +0000253 }
Chris Lattnerf719a522004-05-09 20:41:32 +0000254
255 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
John Criswell85b38052004-10-20 14:38:39 +0000256 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
257 BasicBlock *Successor, unsigned Indent);
Chris Lattner5d190e22002-05-09 20:53:56 +0000258 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
259 unsigned Indent);
Chris Lattner637ee392003-11-25 20:49:55 +0000260 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
261 gep_type_iterator E);
Bill Wendling77a345f2007-02-23 22:45:08 +0000262
263 std::string GetValueName(const Value *Operand);
Sumant Kowshikcf3afd92002-05-08 18:09:58 +0000264 };
Chris Lattner0997f202004-02-14 00:31:10 +0000265}
Sumant Kowshikcf3afd92002-05-08 18:09:58 +0000266
Devang Patel8c78a0b2007-05-03 01:11:54 +0000267char CWriter::ID = 0;
Devang Patel09f162c2007-05-01 21:15:47 +0000268
Chris Lattner9c299912004-05-09 06:20:51 +0000269/// This method inserts names for any unnamed structure types that are used by
270/// the program, and removes names from structure types that are not used by the
271/// program.
272///
Chris Lattnerd2d174d2006-02-13 22:22:42 +0000273bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
Chris Lattner9c299912004-05-09 06:20:51 +0000274 // Get a set of types that are used by the program...
275 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
Misha Brukmanea548c02005-04-20 16:05:03 +0000276
Chris Lattner9c299912004-05-09 06:20:51 +0000277 // Loop over the module symbol table, removing types from UT that are
Chris Lattnerea506202005-03-08 16:19:59 +0000278 // already named, and removing names for types that are not used.
Chris Lattner9c299912004-05-09 06:20:51 +0000279 //
Reid Spencer32af9e82007-01-06 07:24:44 +0000280 TypeSymbolTable &TST = M.getTypeSymbolTable();
281 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
Reid Spencere7e96712004-05-25 08:53:40 +0000282 TI != TE; ) {
Reid Spencer32af9e82007-01-06 07:24:44 +0000283 TypeSymbolTable::iterator I = TI++;
Chris Lattner5488ade2007-01-16 07:22:23 +0000284
285 // If this isn't a struct type, remove it from our set of types to name.
286 // This simplifies emission later.
Chris Lattner4202f372007-01-16 18:02:45 +0000287 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second)) {
Reid Spencer32af9e82007-01-06 07:24:44 +0000288 TST.remove(I);
Chris Lattner5488ade2007-01-16 07:22:23 +0000289 } else {
290 // If this is not used, remove it from the symbol table.
291 std::set<const Type *>::iterator UTI = UT.find(I->second);
292 if (UTI == UT.end())
293 TST.remove(I);
294 else
295 UT.erase(UTI); // Only keep one name for this type.
296 }
Reid Spencere7e96712004-05-25 08:53:40 +0000297 }
Chris Lattner9c299912004-05-09 06:20:51 +0000298
299 // UT now contains types that are not named. Loop over it, naming
300 // structure types.
301 //
302 bool Changed = false;
Chris Lattnerc53c2a32004-05-28 05:47:27 +0000303 unsigned RenameCounter = 0;
Chris Lattner9c299912004-05-09 06:20:51 +0000304 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
305 I != E; ++I)
306 if (const StructType *ST = dyn_cast<StructType>(*I)) {
Chris Lattnerc53c2a32004-05-28 05:47:27 +0000307 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
308 ++RenameCounter;
Chris Lattner9c299912004-05-09 06:20:51 +0000309 Changed = true;
310 }
Chris Lattnerd2d174d2006-02-13 22:22:42 +0000311
312
313 // Loop over all external functions and globals. If we have two with
314 // identical names, merge them.
315 // FIXME: This code should disappear when we don't allow values with the same
316 // names when they have different types!
317 std::map<std::string, GlobalValue*> ExtSymbols;
318 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
319 Function *GV = I++;
Reid Spencer5301e7c2007-01-30 20:08:39 +0000320 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerd2d174d2006-02-13 22:22:42 +0000321 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
322 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
323 if (!X.second) {
324 // Found a conflict, replace this global with the previous one.
325 GlobalValue *OldGV = X.first->second;
Reid Spencerb341b082006-12-12 05:05:00 +0000326 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerd2d174d2006-02-13 22:22:42 +0000327 GV->eraseFromParent();
328 Changed = true;
329 }
330 }
331 }
332 // Do the same for globals.
333 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
334 I != E;) {
335 GlobalVariable *GV = I++;
Reid Spencer5301e7c2007-01-30 20:08:39 +0000336 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerd2d174d2006-02-13 22:22:42 +0000337 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
338 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
339 if (!X.second) {
340 // Found a conflict, replace this global with the previous one.
341 GlobalValue *OldGV = X.first->second;
Reid Spencerb341b082006-12-12 05:05:00 +0000342 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerd2d174d2006-02-13 22:22:42 +0000343 GV->eraseFromParent();
344 Changed = true;
345 }
346 }
347 }
348
Chris Lattner9c299912004-05-09 06:20:51 +0000349 return Changed;
350}
351
Chris Lattnerde177e02006-05-23 23:39:48 +0000352/// printStructReturnPointerFunctionType - This is like printType for a struct
353/// return type, except, instead of printing the type as void (*)(Struct*, ...)
354/// print it as "Struct (*)(...)", for struct return functions.
355void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
356 const PointerType *TheTy) {
357 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
358 std::stringstream FunctionInnards;
359 FunctionInnards << " (*) (";
360 bool PrintedType = false;
361
362 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
363 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
Reid Spencerdf7c61d2007-01-07 03:24:48 +0000364 unsigned Idx = 1;
Reid Spencer71b79e32007-04-09 06:17:21 +0000365 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerde177e02006-05-23 23:39:48 +0000366 for (++I; I != E; ++I) {
367 if (PrintedType)
368 FunctionInnards << ", ";
Reid Spencerdf7c61d2007-01-07 03:24:48 +0000369 printType(FunctionInnards, *I,
Reid Spencera472f662007-04-11 02:44:20 +0000370 /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt), "");
Chris Lattnerde177e02006-05-23 23:39:48 +0000371 PrintedType = true;
372 }
373 if (FTy->isVarArg()) {
374 if (PrintedType)
375 FunctionInnards << ", ...";
376 } else if (!PrintedType) {
377 FunctionInnards << "void";
378 }
379 FunctionInnards << ')';
380 std::string tstr = FunctionInnards.str();
Reid Spencerdf7c61d2007-01-07 03:24:48 +0000381 printType(Out, RetTy,
Reid Spencera472f662007-04-11 02:44:20 +0000382 /*isSigned=*/Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt), tstr);
Chris Lattnerde177e02006-05-23 23:39:48 +0000383}
384
Reid Spencer266e42b2006-12-23 06:05:41 +0000385std::ostream &
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000386CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
Reid Spencer266e42b2006-12-23 06:05:41 +0000387 const std::string &NameSoFar) {
Chris Lattner03c49532007-01-15 02:27:26 +0000388 assert((Ty->isPrimitiveType() || Ty->isInteger()) &&
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000389 "Invalid type for printSimpleType");
Reid Spencer266e42b2006-12-23 06:05:41 +0000390 switch (Ty->getTypeID()) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000391 case Type::VoidTyID: return Out << "void " << NameSoFar;
392 case Type::IntegerTyID: {
393 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
394 if (NumBits == 1)
395 return Out << "bool " << NameSoFar;
396 else if (NumBits <= 8)
397 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
398 else if (NumBits <= 16)
399 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
400 else if (NumBits <= 32)
401 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
402 else {
403 assert(NumBits <= 64 && "Bit widths > 64 not implemented yet");
404 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
405 }
406 }
407 case Type::FloatTyID: return Out << "float " << NameSoFar;
408 case Type::DoubleTyID: return Out << "double " << NameSoFar;
Reid Spencer266e42b2006-12-23 06:05:41 +0000409 default :
410 cerr << "Unknown primitive type: " << *Ty << "\n";
411 abort();
412 }
413}
Chris Lattner9c299912004-05-09 06:20:51 +0000414
Chris Lattner9ccab2c2002-08-19 22:17:53 +0000415// Pass the Type* and the variable name and this prints out the variable
416// declaration.
417//
Chris Lattner57ebe402003-05-03 03:14:35 +0000418std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
Reid Spencerdf7c61d2007-01-07 03:24:48 +0000419 bool isSigned, const std::string &NameSoFar,
Chris Lattner7af7d942003-11-03 01:01:59 +0000420 bool IgnoreName) {
Chris Lattner03c49532007-01-15 02:27:26 +0000421 if (Ty->isPrimitiveType() || Ty->isInteger()) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000422 printSimpleType(Out, Ty, isSigned, NameSoFar);
Reid Spencer266e42b2006-12-23 06:05:41 +0000423 return Out;
424 }
Misha Brukmanea548c02005-04-20 16:05:03 +0000425
Chris Lattner9ccab2c2002-08-19 22:17:53 +0000426 // Check to see if the type is named.
Chris Lattnerc6e5d682002-10-16 00:08:22 +0000427 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattner57ebe402003-05-03 03:14:35 +0000428 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
Misha Brukman2b1e1002005-02-14 18:52:35 +0000429 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
Chris Lattnerc6e5d682002-10-16 00:08:22 +0000430 }
Chris Lattner9ccab2c2002-08-19 22:17:53 +0000431
Chris Lattner6b727592004-06-17 18:19:28 +0000432 switch (Ty->getTypeID()) {
Chris Lattner9ccab2c2002-08-19 22:17:53 +0000433 case Type::FunctionTyID: {
Chris Lattnerde177e02006-05-23 23:39:48 +0000434 const FunctionType *FTy = cast<FunctionType>(Ty);
Misha Brukmanea548c02005-04-20 16:05:03 +0000435 std::stringstream FunctionInnards;
Joel Stanleyfbb9ab42003-06-25 04:52:09 +0000436 FunctionInnards << " (" << NameSoFar << ") (";
Reid Spencer71b79e32007-04-09 06:17:21 +0000437 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Reid Spencerdf7c61d2007-01-07 03:24:48 +0000438 unsigned Idx = 1;
Chris Lattnerde177e02006-05-23 23:39:48 +0000439 for (FunctionType::param_iterator I = FTy->param_begin(),
440 E = FTy->param_end(); I != E; ++I) {
441 if (I != FTy->param_begin())
Joel Stanleyfbb9ab42003-06-25 04:52:09 +0000442 FunctionInnards << ", ";
Reid Spencerdf7c61d2007-01-07 03:24:48 +0000443 printType(FunctionInnards, *I,
Reid Spencera472f662007-04-11 02:44:20 +0000444 /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt), "");
Reid Spencerdf7c61d2007-01-07 03:24:48 +0000445 ++Idx;
Chris Lattner9ccab2c2002-08-19 22:17:53 +0000446 }
Chris Lattnerde177e02006-05-23 23:39:48 +0000447 if (FTy->isVarArg()) {
448 if (FTy->getNumParams())
Reid Spencere7e96712004-05-25 08:53:40 +0000449 FunctionInnards << ", ...";
Chris Lattnerde177e02006-05-23 23:39:48 +0000450 } else if (!FTy->getNumParams()) {
Joel Stanleyfbb9ab42003-06-25 04:52:09 +0000451 FunctionInnards << "void";
Chris Lattner9ccab2c2002-08-19 22:17:53 +0000452 }
Misha Brukman2b1e1002005-02-14 18:52:35 +0000453 FunctionInnards << ')';
Joel Stanleyfbb9ab42003-06-25 04:52:09 +0000454 std::string tstr = FunctionInnards.str();
Reid Spencerdf7c61d2007-01-07 03:24:48 +0000455 printType(Out, FTy->getReturnType(),
Reid Spencera472f662007-04-11 02:44:20 +0000456 /*isSigned=*/Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt), tstr);
Nick Hildenbrandtcdf2a182002-11-18 20:55:50 +0000457 return Out;
Chris Lattner9ccab2c2002-08-19 22:17:53 +0000458 }
459 case Type::StructTyID: {
460 const StructType *STy = cast<StructType>(Ty);
461 Out << NameSoFar + " {\n";
462 unsigned Idx = 0;
Chris Lattnerac6db752004-02-09 04:37:31 +0000463 for (StructType::element_iterator I = STy->element_begin(),
464 E = STy->element_end(); I != E; ++I) {
Chris Lattner9ccab2c2002-08-19 22:17:53 +0000465 Out << " ";
Reid Spencer1fc9be32007-01-09 17:09:09 +0000466 printType(Out, *I, false, "field" + utostr(Idx++));
Chris Lattner9ccab2c2002-08-19 22:17:53 +0000467 Out << ";\n";
468 }
Lauro Ramos Venancio3d708552007-07-11 19:56:53 +0000469 Out << '}';
470 if (STy->isPacked())
471 Out << " __attribute__ ((packed))";
472 return Out;
Misha Brukmanea548c02005-04-20 16:05:03 +0000473 }
Chris Lattner9ccab2c2002-08-19 22:17:53 +0000474
475 case Type::PointerTyID: {
476 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve8a5c9b12002-08-25 20:00:08 +0000477 std::string ptrName = "*" + NameSoFar;
478
Robert Bocchino4b41c8e2006-01-20 20:43:57 +0000479 if (isa<ArrayType>(PTy->getElementType()) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +0000480 isa<VectorType>(PTy->getElementType()))
Chris Lattner7be3ab22003-11-03 04:31:54 +0000481 ptrName = "(" + ptrName + ")";
Vikram S. Adve8a5c9b12002-08-25 20:00:08 +0000482
Reid Spencer1fc9be32007-01-09 17:09:09 +0000483 return printType(Out, PTy->getElementType(), false, ptrName);
Misha Brukman96c8d592003-07-21 16:34:35 +0000484 }
Chris Lattner9ccab2c2002-08-19 22:17:53 +0000485
486 case Type::ArrayTyID: {
487 const ArrayType *ATy = cast<ArrayType>(Ty);
488 unsigned NumElements = ATy->getNumElements();
Chris Lattner298a7f82004-12-15 23:13:15 +0000489 if (NumElements == 0) NumElements = 1;
Reid Spencer1fc9be32007-01-09 17:09:09 +0000490 return printType(Out, ATy->getElementType(), false,
Chris Lattner9ccab2c2002-08-19 22:17:53 +0000491 NameSoFar + "[" + utostr(NumElements) + "]");
492 }
Chris Lattnerc6e5d682002-10-16 00:08:22 +0000493
Reid Spencerd84d35b2007-02-15 02:26:10 +0000494 case Type::VectorTyID: {
495 const VectorType *PTy = cast<VectorType>(Ty);
Robert Bocchino4b41c8e2006-01-20 20:43:57 +0000496 unsigned NumElements = PTy->getNumElements();
497 if (NumElements == 0) NumElements = 1;
Reid Spencer1fc9be32007-01-09 17:09:09 +0000498 return printType(Out, PTy->getElementType(), false,
Robert Bocchino4b41c8e2006-01-20 20:43:57 +0000499 NameSoFar + "[" + utostr(NumElements) + "]");
500 }
501
Chris Lattnerc6e5d682002-10-16 00:08:22 +0000502 case Type::OpaqueTyID: {
503 static int Count = 0;
Chris Lattner57ebe402003-05-03 03:14:35 +0000504 std::string TyName = "struct opaque_" + itostr(Count++);
Chris Lattnerc6e5d682002-10-16 00:08:22 +0000505 assert(TypeNames.find(Ty) == TypeNames.end());
506 TypeNames[Ty] = TyName;
Misha Brukman2b1e1002005-02-14 18:52:35 +0000507 return Out << TyName << ' ' << NameSoFar;
Chris Lattnerc6e5d682002-10-16 00:08:22 +0000508 }
Chris Lattner9ccab2c2002-08-19 22:17:53 +0000509 default:
510 assert(0 && "Unhandled case in getTypeProps!");
511 abort();
512 }
513
514 return Out;
515}
516
Chris Lattnerfda3b292002-08-19 21:32:41 +0000517void CWriter::printConstantArray(ConstantArray *CPA) {
518
519 // As a special case, print the array as a string if it is an array of
520 // ubytes or an array of sbytes with positive values.
Misha Brukmanea548c02005-04-20 16:05:03 +0000521 //
Chris Lattnerfda3b292002-08-19 21:32:41 +0000522 const Type *ETy = CPA->getType()->getElementType();
Reid Spencere63b6512006-12-31 05:55:36 +0000523 bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty);
Chris Lattnerfda3b292002-08-19 21:32:41 +0000524
525 // Make sure the last character is a null char, as automatically added by C
Chris Lattnerd994fd32003-06-16 12:09:09 +0000526 if (isString && (CPA->getNumOperands() == 0 ||
527 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattnerfda3b292002-08-19 21:32:41 +0000528 isString = false;
Misha Brukmanea548c02005-04-20 16:05:03 +0000529
Chris Lattnerfda3b292002-08-19 21:32:41 +0000530 if (isString) {
Misha Brukman2b1e1002005-02-14 18:52:35 +0000531 Out << '\"';
Chris Lattnerd994fd32003-06-16 12:09:09 +0000532 // Keep track of whether the last number was a hexadecimal escape
533 bool LastWasHex = false;
534
Chris Lattnerfda3b292002-08-19 21:32:41 +0000535 // Do not include the last character, which we know is null
536 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000537 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
Misha Brukmanea548c02005-04-20 16:05:03 +0000538
Chris Lattnerd994fd32003-06-16 12:09:09 +0000539 // Print it out literally if it is a printable character. The only thing
540 // to be careful about is when the last letter output was a hex escape
541 // code, in which case we have to be careful not to print out hex digits
Chris Lattner71ec97a2003-06-16 12:21:19 +0000542 // explicitly (the C compiler thinks it is a continuation of the previous
543 // character, sheesh...)
Chris Lattnerd994fd32003-06-16 12:09:09 +0000544 //
545 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
546 LastWasHex = false;
Nick Hildenbrandt642f44f2002-11-06 21:40:23 +0000547 if (C == '"' || C == '\\')
548 Out << "\\" << C;
Nick Hildenbrandt386834b2002-09-30 21:11:55 +0000549 else
550 Out << C;
Chris Lattnerfda3b292002-08-19 21:32:41 +0000551 } else {
Chris Lattnerd994fd32003-06-16 12:09:09 +0000552 LastWasHex = false;
Chris Lattnerfda3b292002-08-19 21:32:41 +0000553 switch (C) {
554 case '\n': Out << "\\n"; break;
555 case '\t': Out << "\\t"; break;
556 case '\r': Out << "\\r"; break;
557 case '\v': Out << "\\v"; break;
558 case '\a': Out << "\\a"; break;
Nick Hildenbrandt386834b2002-09-30 21:11:55 +0000559 case '\"': Out << "\\\""; break;
Misha Brukmanea548c02005-04-20 16:05:03 +0000560 case '\'': Out << "\\\'"; break;
Chris Lattnerfda3b292002-08-19 21:32:41 +0000561 default:
562 Out << "\\x";
Chris Lattnerd994fd32003-06-16 12:09:09 +0000563 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
564 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
565 LastWasHex = true;
Chris Lattnerfda3b292002-08-19 21:32:41 +0000566 break;
567 }
568 }
569 }
Misha Brukman2b1e1002005-02-14 18:52:35 +0000570 Out << '\"';
Chris Lattnerfda3b292002-08-19 21:32:41 +0000571 } else {
Misha Brukman2b1e1002005-02-14 18:52:35 +0000572 Out << '{';
Chris Lattnerfda3b292002-08-19 21:32:41 +0000573 if (CPA->getNumOperands()) {
Misha Brukman2b1e1002005-02-14 18:52:35 +0000574 Out << ' ';
Chris Lattnerfda3b292002-08-19 21:32:41 +0000575 printConstant(cast<Constant>(CPA->getOperand(0)));
576 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
577 Out << ", ";
578 printConstant(cast<Constant>(CPA->getOperand(i)));
579 }
580 }
581 Out << " }";
582 }
583}
584
Reid Spencerd84d35b2007-02-15 02:26:10 +0000585void CWriter::printConstantVector(ConstantVector *CP) {
Robert Bocchino4b41c8e2006-01-20 20:43:57 +0000586 Out << '{';
587 if (CP->getNumOperands()) {
588 Out << ' ';
589 printConstant(cast<Constant>(CP->getOperand(0)));
590 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
591 Out << ", ";
592 printConstant(cast<Constant>(CP->getOperand(i)));
593 }
594 }
595 Out << " }";
596}
597
Chris Lattner6e7ae582003-10-05 00:40:51 +0000598// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
599// textually as a double (rather than as a reference to a stack-allocated
600// variable). We decide this by converting CFP to a string and back into a
601// double, and then checking whether the conversion results in a bit-equal
602// double to the original value of CFP. This depends on us and the target C
603// compiler agreeing on the conversion process (which is pretty likely since we
604// only deal in IEEE FP).
605//
Chris Lattnerf719a522004-05-09 20:41:32 +0000606static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000607 APFloat APF = APFloat(CFP->getValueAPF()); // copy
608 if (CFP->getType()==Type::FloatTy)
609 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
Reid Spencer35b927e02006-11-05 19:26:37 +0000610#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Chris Lattner1d243162003-10-12 08:12:58 +0000611 char Buffer[100];
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000612 sprintf(Buffer, "%a", APF.convertToDouble());
Chris Lattner1d243162003-10-12 08:12:58 +0000613 if (!strncmp(Buffer, "0x", 2) ||
614 !strncmp(Buffer, "-0x", 3) ||
615 !strncmp(Buffer, "+0x", 3))
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000616 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
Chris Lattner1d243162003-10-12 08:12:58 +0000617 return false;
618#else
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000619 std::string StrVal = ftostr(APF);
Chris Lattner5d841b22003-10-12 04:36:29 +0000620
621 while (StrVal[0] == ' ')
622 StrVal.erase(StrVal.begin());
623
Chris Lattner6e7ae582003-10-05 00:40:51 +0000624 // Check to make sure that the stringized number is not some string like "Inf"
625 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaeke87b4f072003-06-17 23:55:35 +0000626 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
627 ((StrVal[0] == '-' || StrVal[0] == '+') &&
628 (StrVal[1] >= '0' && StrVal[1] <= '9')))
629 // Reparse stringized version!
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000630 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
Brian Gaeke87b4f072003-06-17 23:55:35 +0000631 return false;
Chris Lattner1d243162003-10-12 08:12:58 +0000632#endif
Brian Gaeke87b4f072003-06-17 23:55:35 +0000633}
Chris Lattnerfda3b292002-08-19 21:32:41 +0000634
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000635/// Print out the casting for a cast operation. This does the double casting
636/// necessary for conversion to the destination type, if necessary.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000637/// @brief Print a cast
638void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000639 // Print the destination type cast
640 switch (opc) {
641 case Instruction::UIToFP:
642 case Instruction::SIToFP:
643 case Instruction::IntToPtr:
644 case Instruction::Trunc:
645 case Instruction::BitCast:
646 case Instruction::FPExt:
647 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
648 Out << '(';
649 printType(Out, DstTy);
650 Out << ')';
651 break;
652 case Instruction::ZExt:
653 case Instruction::PtrToInt:
654 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
655 Out << '(';
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000656 printSimpleType(Out, DstTy, false);
Reid Spencer266e42b2006-12-23 06:05:41 +0000657 Out << ')';
658 break;
659 case Instruction::SExt:
660 case Instruction::FPToSI: // For these, make sure we get a signed dest
661 Out << '(';
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000662 printSimpleType(Out, DstTy, true);
Reid Spencer266e42b2006-12-23 06:05:41 +0000663 Out << ')';
664 break;
665 default:
666 assert(0 && "Invalid cast opcode");
667 }
668
669 // Print the source type cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000670 switch (opc) {
671 case Instruction::UIToFP:
672 case Instruction::ZExt:
Reid Spencer266e42b2006-12-23 06:05:41 +0000673 Out << '(';
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000674 printSimpleType(Out, SrcTy, false);
Reid Spencer266e42b2006-12-23 06:05:41 +0000675 Out << ')';
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000676 break;
677 case Instruction::SIToFP:
678 case Instruction::SExt:
Reid Spencer266e42b2006-12-23 06:05:41 +0000679 Out << '(';
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000680 printSimpleType(Out, SrcTy, true);
Reid Spencer266e42b2006-12-23 06:05:41 +0000681 Out << ')';
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000682 break;
683 case Instruction::IntToPtr:
684 case Instruction::PtrToInt:
Reid Spencer266e42b2006-12-23 06:05:41 +0000685 // Avoid "cast to pointer from integer of different size" warnings
686 Out << "(unsigned long)";
687 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000688 case Instruction::Trunc:
689 case Instruction::BitCast:
690 case Instruction::FPExt:
691 case Instruction::FPTrunc:
692 case Instruction::FPToSI:
693 case Instruction::FPToUI:
Reid Spencer266e42b2006-12-23 06:05:41 +0000694 break; // These don't need a source cast.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000695 default:
Reid Spencer266e42b2006-12-23 06:05:41 +0000696 assert(0 && "Invalid cast opcode");
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000697 break;
698 }
699}
700
Chris Lattnerfda3b292002-08-19 21:32:41 +0000701// printConstant - The LLVM Constant to C Constant converter.
702void CWriter::printConstant(Constant *CPV) {
703 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
704 switch (CE->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000705 case Instruction::Trunc:
706 case Instruction::ZExt:
707 case Instruction::SExt:
708 case Instruction::FPTrunc:
709 case Instruction::FPExt:
710 case Instruction::UIToFP:
711 case Instruction::SIToFP:
712 case Instruction::FPToUI:
713 case Instruction::FPToSI:
714 case Instruction::PtrToInt:
715 case Instruction::IntToPtr:
716 case Instruction::BitCast:
717 Out << "(";
718 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
Chris Lattner4995f922007-05-03 02:57:13 +0000719 if (CE->getOpcode() == Instruction::SExt &&
720 CE->getOperand(0)->getType() == Type::Int1Ty) {
Reid Spencerf3aa9322007-05-02 02:17:41 +0000721 // Make sure we really sext from bool here by subtracting from 0
722 Out << "0-";
Reid Spencerf3aa9322007-05-02 02:17:41 +0000723 }
Chris Lattner4995f922007-05-03 02:57:13 +0000724 printConstant(CE->getOperand(0));
725 if (CE->getType() == Type::Int1Ty &&
726 (CE->getOpcode() == Instruction::Trunc ||
727 CE->getOpcode() == Instruction::FPToUI ||
728 CE->getOpcode() == Instruction::FPToSI ||
729 CE->getOpcode() == Instruction::PtrToInt)) {
730 // Make sure we really truncate to bool here by anding with 1
731 Out << "&1u";
732 }
733 Out << ')';
Chris Lattnerf3a86f02002-08-19 23:09:46 +0000734 return;
Chris Lattner4995f922007-05-03 02:57:13 +0000735
Chris Lattnerf3a86f02002-08-19 23:09:46 +0000736 case Instruction::GetElementPtr:
Nick Hildenbrandtafff0a22002-10-03 20:47:24 +0000737 Out << "(&(";
Chris Lattner637ee392003-11-25 20:49:55 +0000738 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
739 gep_type_end(CPV));
Nick Hildenbrandtafff0a22002-10-03 20:47:24 +0000740 Out << "))";
Chris Lattnerf3a86f02002-08-19 23:09:46 +0000741 return;
Chris Lattnerb28dd112004-04-01 05:28:26 +0000742 case Instruction::Select:
Misha Brukman2b1e1002005-02-14 18:52:35 +0000743 Out << '(';
Chris Lattnerb28dd112004-04-01 05:28:26 +0000744 printConstant(CE->getOperand(0));
Misha Brukman2b1e1002005-02-14 18:52:35 +0000745 Out << '?';
Chris Lattnerb28dd112004-04-01 05:28:26 +0000746 printConstant(CE->getOperand(1));
Misha Brukman2b1e1002005-02-14 18:52:35 +0000747 Out << ':';
Chris Lattnerb28dd112004-04-01 05:28:26 +0000748 printConstant(CE->getOperand(2));
Misha Brukman2b1e1002005-02-14 18:52:35 +0000749 Out << ')';
Chris Lattnerb28dd112004-04-01 05:28:26 +0000750 return;
Chris Lattnerf3a86f02002-08-19 23:09:46 +0000751 case Instruction::Add:
Chris Lattnerf3a86f02002-08-19 23:09:46 +0000752 case Instruction::Sub:
Chris Lattner47be9512003-08-14 19:19:53 +0000753 case Instruction::Mul:
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000754 case Instruction::SDiv:
755 case Instruction::UDiv:
756 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +0000757 case Instruction::URem:
758 case Instruction::SRem:
759 case Instruction::FRem:
Chris Lattner93feeb12004-12-29 04:00:09 +0000760 case Instruction::And:
761 case Instruction::Or:
762 case Instruction::Xor:
Reid Spencer266e42b2006-12-23 06:05:41 +0000763 case Instruction::ICmp:
Brian Gaeke03f36112003-11-22 05:02:56 +0000764 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +0000765 case Instruction::LShr:
766 case Instruction::AShr:
Reid Spencerc6b52da2006-10-26 06:17:40 +0000767 {
Misha Brukman2b1e1002005-02-14 18:52:35 +0000768 Out << '(';
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000769 bool NeedsClosingParens = printConstExprCast(CE);
770 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
Chris Lattner47be9512003-08-14 19:19:53 +0000771 switch (CE->getOpcode()) {
772 case Instruction::Add: Out << " + "; break;
773 case Instruction::Sub: Out << " - "; break;
774 case Instruction::Mul: Out << " * "; break;
Reid Spencer7eb55b32006-11-02 01:53:59 +0000775 case Instruction::URem:
776 case Instruction::SRem:
777 case Instruction::FRem: Out << " % "; break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000778 case Instruction::UDiv:
779 case Instruction::SDiv:
780 case Instruction::FDiv: Out << " / "; break;
Chris Lattner93feeb12004-12-29 04:00:09 +0000781 case Instruction::And: Out << " & "; break;
782 case Instruction::Or: Out << " | "; break;
783 case Instruction::Xor: Out << " ^ "; break;
Brian Gaeke03f36112003-11-22 05:02:56 +0000784 case Instruction::Shl: Out << " << "; break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000785 case Instruction::LShr:
786 case Instruction::AShr: Out << " >> "; break;
Reid Spencer266e42b2006-12-23 06:05:41 +0000787 case Instruction::ICmp:
788 switch (CE->getPredicate()) {
789 case ICmpInst::ICMP_EQ: Out << " == "; break;
790 case ICmpInst::ICMP_NE: Out << " != "; break;
791 case ICmpInst::ICMP_SLT:
792 case ICmpInst::ICMP_ULT: Out << " < "; break;
793 case ICmpInst::ICMP_SLE:
794 case ICmpInst::ICMP_ULE: Out << " <= "; break;
795 case ICmpInst::ICMP_SGT:
796 case ICmpInst::ICMP_UGT: Out << " > "; break;
797 case ICmpInst::ICMP_SGE:
798 case ICmpInst::ICMP_UGE: Out << " >= "; break;
799 default: assert(0 && "Illegal ICmp predicate");
800 }
801 break;
Chris Lattner47be9512003-08-14 19:19:53 +0000802 default: assert(0 && "Illegal opcode here!");
803 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000804 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
805 if (NeedsClosingParens)
806 Out << "))";
Misha Brukman2b1e1002005-02-14 18:52:35 +0000807 Out << ')';
Chris Lattnerf3a86f02002-08-19 23:09:46 +0000808 return;
Reid Spencerc6b52da2006-10-26 06:17:40 +0000809 }
Reid Spencer13cae7c2007-01-08 06:58:32 +0000810 case Instruction::FCmp: {
811 Out << '(';
812 bool NeedsClosingParens = printConstExprCast(CE);
813 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
814 Out << "0";
815 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
816 Out << "1";
817 else {
818 const char* op = 0;
819 switch (CE->getPredicate()) {
820 default: assert(0 && "Illegal FCmp predicate");
821 case FCmpInst::FCMP_ORD: op = "ord"; break;
822 case FCmpInst::FCMP_UNO: op = "uno"; break;
823 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
824 case FCmpInst::FCMP_UNE: op = "une"; break;
825 case FCmpInst::FCMP_ULT: op = "ult"; break;
826 case FCmpInst::FCMP_ULE: op = "ule"; break;
827 case FCmpInst::FCMP_UGT: op = "ugt"; break;
828 case FCmpInst::FCMP_UGE: op = "uge"; break;
829 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
830 case FCmpInst::FCMP_ONE: op = "one"; break;
831 case FCmpInst::FCMP_OLT: op = "olt"; break;
832 case FCmpInst::FCMP_OLE: op = "ole"; break;
833 case FCmpInst::FCMP_OGT: op = "ogt"; break;
834 case FCmpInst::FCMP_OGE: op = "oge"; break;
835 }
836 Out << "llvm_fcmp_" << op << "(";
837 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
838 Out << ", ";
839 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
840 Out << ")";
841 }
842 if (NeedsClosingParens)
843 Out << "))";
844 Out << ')';
845 }
Chris Lattnerfda3b292002-08-19 21:32:41 +0000846 default:
Bill Wendling9bfb1e12006-12-07 22:21:48 +0000847 cerr << "CWriter Error: Unhandled constant expression: "
848 << *CE << "\n";
Chris Lattnerfda3b292002-08-19 21:32:41 +0000849 abort();
850 }
Chris Lattner583dfdc2004-10-16 18:12:13 +0000851 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
Chris Lattner621c4132004-10-17 17:48:59 +0000852 Out << "((";
Reid Spencer266e42b2006-12-23 06:05:41 +0000853 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattner621c4132004-10-17 17:48:59 +0000854 Out << ")/*UNDEF*/0)";
Chris Lattner583dfdc2004-10-16 18:12:13 +0000855 return;
Chris Lattnerfda3b292002-08-19 21:32:41 +0000856 }
857
Reid Spencerc0b86d52007-01-08 08:00:00 +0000858 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
859 const Type* Ty = CI->getType();
Reid Spencer542964f2007-01-11 18:21:29 +0000860 if (Ty == Type::Int1Ty)
Reid Spencercddc9df2007-01-12 04:24:46 +0000861 Out << (CI->getZExtValue() ? '1' : '0') ;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000862 else {
863 Out << "((";
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000864 printSimpleType(Out, Ty, false) << ')';
Zhou Sheng75b871f2007-01-11 12:24:14 +0000865 if (CI->isMinValue(true))
866 Out << CI->getZExtValue() << 'u';
867 else
868 Out << CI->getSExtValue();
869 if (Ty->getPrimitiveSizeInBits() > 32)
870 Out << "ll";
871 Out << ')';
872 }
Reid Spencerc0b86d52007-01-08 08:00:00 +0000873 return;
874 }
875
876 switch (CPV->getType()->getTypeID()) {
Chris Lattnerfda3b292002-08-19 21:32:41 +0000877 case Type::FloatTyID:
Chris Lattner230d8322002-09-20 23:26:33 +0000878 case Type::DoubleTyID: {
879 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattner57ebe402003-05-03 03:14:35 +0000880 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattner230d8322002-09-20 23:26:33 +0000881 if (I != FPConstantMap.end()) {
882 // Because of FP precision problems we must load from a stack allocated
883 // value that holds the value in hex.
884 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
Misha Brukman2b1e1002005-02-14 18:52:35 +0000885 << "*)&FPConstant" << I->second << ')';
Chris Lattner230d8322002-09-20 23:26:33 +0000886 } else {
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000887 double V = FPC->getType() == Type::FloatTy ?
888 FPC->getValueAPF().convertToFloat() :
889 FPC->getValueAPF().convertToDouble();
890 if (IsNAN(V)) {
Brian Gaeke1dde3fa2004-07-21 03:15:26 +0000891 // The value is NaN
Misha Brukmanea548c02005-04-20 16:05:03 +0000892
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000893 // FIXME the actual NaN bits should be emitted.
Brian Gaeke35eb7ae2004-08-25 19:00:42 +0000894 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
895 // it's 0x7ff4.
896 const unsigned long QuietNaN = 0x7ff8UL;
Reid Spencerde46e482006-11-02 20:25:50 +0000897 //const unsigned long SignalNaN = 0x7ff4UL;
Brian Gaeke35eb7ae2004-08-25 19:00:42 +0000898
899 // We need to grab the first part of the FP #
Brian Gaeke35eb7ae2004-08-25 19:00:42 +0000900 char Buffer[100];
901
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000902 uint64_t ll = DoubleToBits(V);
Reid Spencerff825962006-05-31 22:26:11 +0000903 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
Brian Gaeke35eb7ae2004-08-25 19:00:42 +0000904
905 std::string Num(&Buffer[0], &Buffer[6]);
906 unsigned long Val = strtoul(Num.c_str(), 0, 16);
907
Brian Gaeke1dde3fa2004-07-21 03:15:26 +0000908 if (FPC->getType() == Type::FloatTy)
Brian Gaeke35eb7ae2004-08-25 19:00:42 +0000909 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
910 << Buffer << "\") /*nan*/ ";
Brian Gaeke1dde3fa2004-07-21 03:15:26 +0000911 else
Brian Gaeke35eb7ae2004-08-25 19:00:42 +0000912 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
913 << Buffer << "\") /*nan*/ ";
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000914 } else if (IsInf(V)) {
Brian Gaeke1dde3fa2004-07-21 03:15:26 +0000915 // The value is Inf
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000916 if (V < 0) Out << '-';
Brian Gaeke35eb7ae2004-08-25 19:00:42 +0000917 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
918 << " /*inf*/ ";
Brian Gaeke1dde3fa2004-07-21 03:15:26 +0000919 } else {
Brian Gaeke7f007532004-08-25 19:37:26 +0000920 std::string Num;
Reid Spencer35b927e02006-11-05 19:26:37 +0000921#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Brian Gaeke7f007532004-08-25 19:37:26 +0000922 // Print out the constant as a floating point number.
923 char Buffer[100];
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000924 sprintf(Buffer, "%a", V);
Brian Gaeke7f007532004-08-25 19:37:26 +0000925 Num = Buffer;
926#else
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000927 Num = ftostr(FPC->getValueAPF());
Brian Gaeke7f007532004-08-25 19:37:26 +0000928#endif
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000929 Out << Num;
Brian Gaeke1dde3fa2004-07-21 03:15:26 +0000930 }
Chris Lattner230d8322002-09-20 23:26:33 +0000931 }
932 break;
933 }
Chris Lattnerfda3b292002-08-19 21:32:41 +0000934
935 case Type::ArrayTyID:
Chris Lattner583dfdc2004-10-16 18:12:13 +0000936 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattner7bea8082004-02-15 05:54:27 +0000937 const ArrayType *AT = cast<ArrayType>(CPV->getType());
Misha Brukman2b1e1002005-02-14 18:52:35 +0000938 Out << '{';
Chris Lattner7bea8082004-02-15 05:54:27 +0000939 if (AT->getNumElements()) {
Misha Brukman2b1e1002005-02-14 18:52:35 +0000940 Out << ' ';
Chris Lattner7bea8082004-02-15 05:54:27 +0000941 Constant *CZ = Constant::getNullValue(AT->getElementType());
942 printConstant(CZ);
943 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
944 Out << ", ";
945 printConstant(CZ);
946 }
947 }
948 Out << " }";
949 } else {
950 printConstantArray(cast<ConstantArray>(CPV));
951 }
Chris Lattnerfda3b292002-08-19 21:32:41 +0000952 break;
953
Reid Spencerd84d35b2007-02-15 02:26:10 +0000954 case Type::VectorTyID:
Robert Bocchino4b41c8e2006-01-20 20:43:57 +0000955 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000956 const VectorType *AT = cast<VectorType>(CPV->getType());
Robert Bocchino4b41c8e2006-01-20 20:43:57 +0000957 Out << '{';
958 if (AT->getNumElements()) {
959 Out << ' ';
960 Constant *CZ = Constant::getNullValue(AT->getElementType());
961 printConstant(CZ);
962 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
963 Out << ", ";
964 printConstant(CZ);
965 }
966 }
967 Out << " }";
968 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000969 printConstantVector(cast<ConstantVector>(CPV));
Robert Bocchino4b41c8e2006-01-20 20:43:57 +0000970 }
971 break;
972
Chris Lattner7bea8082004-02-15 05:54:27 +0000973 case Type::StructTyID:
Chris Lattner583dfdc2004-10-16 18:12:13 +0000974 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattner7bea8082004-02-15 05:54:27 +0000975 const StructType *ST = cast<StructType>(CPV->getType());
Misha Brukman2b1e1002005-02-14 18:52:35 +0000976 Out << '{';
Chris Lattner7bea8082004-02-15 05:54:27 +0000977 if (ST->getNumElements()) {
Misha Brukman2b1e1002005-02-14 18:52:35 +0000978 Out << ' ';
Chris Lattner7bea8082004-02-15 05:54:27 +0000979 printConstant(Constant::getNullValue(ST->getElementType(0)));
980 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
981 Out << ", ";
982 printConstant(Constant::getNullValue(ST->getElementType(i)));
983 }
Chris Lattnerfda3b292002-08-19 21:32:41 +0000984 }
Chris Lattner7bea8082004-02-15 05:54:27 +0000985 Out << " }";
986 } else {
Misha Brukman2b1e1002005-02-14 18:52:35 +0000987 Out << '{';
Chris Lattner7bea8082004-02-15 05:54:27 +0000988 if (CPV->getNumOperands()) {
Misha Brukman2b1e1002005-02-14 18:52:35 +0000989 Out << ' ';
Chris Lattner7bea8082004-02-15 05:54:27 +0000990 printConstant(cast<Constant>(CPV->getOperand(0)));
991 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
992 Out << ", ";
993 printConstant(cast<Constant>(CPV->getOperand(i)));
994 }
995 }
996 Out << " }";
Chris Lattnerfda3b292002-08-19 21:32:41 +0000997 }
Chris Lattnerfda3b292002-08-19 21:32:41 +0000998 break;
Chris Lattnerfda3b292002-08-19 21:32:41 +0000999
1000 case Type::PointerTyID:
Chris Lattner5d190e22002-05-09 20:53:56 +00001001 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattner239ff502003-06-02 03:10:53 +00001002 Out << "((";
Reid Spencer266e42b2006-12-23 06:05:41 +00001003 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattner239ff502003-06-02 03:10:53 +00001004 Out << ")/*NULL*/0)";
Chris Lattnerfda3b292002-08-19 21:32:41 +00001005 break;
Reid Spencercb3fb5d2004-07-18 00:44:37 +00001006 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1007 writeOperand(GV);
Chris Lattnerfda3b292002-08-19 21:32:41 +00001008 break;
1009 }
1010 // FALL THROUGH
1011 default:
Bill Wendling9bfb1e12006-12-07 22:21:48 +00001012 cerr << "Unknown constant type: " << *CPV << "\n";
Chris Lattnerfda3b292002-08-19 21:32:41 +00001013 abort();
1014 }
1015}
1016
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001017// Some constant expressions need to be casted back to the original types
1018// because their operands were casted to the expected type. This function takes
1019// care of detecting that case and printing the cast for the ConstantExpr.
1020bool CWriter::printConstExprCast(const ConstantExpr* CE) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001021 bool NeedsExplicitCast = false;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001022 const Type *Ty = CE->getOperand(0)->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00001023 bool TypeIsSigned = false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001024 switch (CE->getOpcode()) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001025 case Instruction::LShr:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001026 case Instruction::URem:
Reid Spencer266e42b2006-12-23 06:05:41 +00001027 case Instruction::UDiv: NeedsExplicitCast = true; break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001028 case Instruction::AShr:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001029 case Instruction::SRem:
Reid Spencer266e42b2006-12-23 06:05:41 +00001030 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001031 case Instruction::SExt:
Reid Spencer266e42b2006-12-23 06:05:41 +00001032 Ty = CE->getType();
1033 NeedsExplicitCast = true;
1034 TypeIsSigned = true;
1035 break;
1036 case Instruction::ZExt:
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001037 case Instruction::Trunc:
1038 case Instruction::FPTrunc:
1039 case Instruction::FPExt:
1040 case Instruction::UIToFP:
1041 case Instruction::SIToFP:
1042 case Instruction::FPToUI:
1043 case Instruction::FPToSI:
1044 case Instruction::PtrToInt:
1045 case Instruction::IntToPtr:
1046 case Instruction::BitCast:
1047 Ty = CE->getType();
1048 NeedsExplicitCast = true;
1049 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001050 default: break;
1051 }
Reid Spencerfdff9382006-11-08 06:47:33 +00001052 if (NeedsExplicitCast) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001053 Out << "((";
Chris Lattner03c49532007-01-15 02:27:26 +00001054 if (Ty->isInteger() && Ty != Type::Int1Ty)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001055 printSimpleType(Out, Ty, TypeIsSigned);
Reid Spencer266e42b2006-12-23 06:05:41 +00001056 else
Reid Spencer1fc9be32007-01-09 17:09:09 +00001057 printType(Out, Ty); // not integer, sign doesn't matter
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001058 Out << ")(";
1059 }
Reid Spencerfdff9382006-11-08 06:47:33 +00001060 return NeedsExplicitCast;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001061}
1062
1063// Print a constant assuming that it is the operand for a given Opcode. The
1064// opcodes that care about sign need to cast their operands to the expected
1065// type before the operation proceeds. This function does the casting.
1066void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1067
1068 // Extract the operand's type, we'll need it.
1069 const Type* OpTy = CPV->getType();
1070
1071 // Indicate whether to do the cast or not.
1072 bool shouldCast = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00001073 bool typeIsSigned = false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001074
1075 // Based on the Opcode for which this Constant is being written, determine
1076 // the new type to which the operand should be casted by setting the value
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001077 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1078 // casted below.
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001079 switch (Opcode) {
1080 default:
1081 // for most instructions, it doesn't matter
1082 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001083 case Instruction::LShr:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001084 case Instruction::UDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001085 case Instruction::URem:
Reid Spencer266e42b2006-12-23 06:05:41 +00001086 shouldCast = true;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001087 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001088 case Instruction::AShr:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001089 case Instruction::SDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001090 case Instruction::SRem:
Reid Spencer266e42b2006-12-23 06:05:41 +00001091 shouldCast = true;
1092 typeIsSigned = true;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001093 break;
1094 }
1095
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001096 // Write out the casted constant if we should, otherwise just write the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001097 // operand.
1098 if (shouldCast) {
1099 Out << "((";
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001100 printSimpleType(Out, OpTy, typeIsSigned);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001101 Out << ")";
1102 printConstant(CPV);
1103 Out << ")";
1104 } else
Reid Spencer266e42b2006-12-23 06:05:41 +00001105 printConstant(CPV);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001106}
1107
Bill Wendling77a345f2007-02-23 22:45:08 +00001108std::string CWriter::GetValueName(const Value *Operand) {
1109 std::string Name;
1110
1111 if (!isa<GlobalValue>(Operand) && Operand->getName() != "") {
1112 std::string VarName;
1113
1114 Name = Operand->getName();
1115 VarName.reserve(Name.capacity());
1116
1117 for (std::string::iterator I = Name.begin(), E = Name.end();
1118 I != E; ++I) {
1119 char ch = *I;
1120
1121 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1122 (ch >= '0' && ch <= '9') || ch == '_'))
1123 VarName += '_';
1124 else
1125 VarName += ch;
1126 }
1127
1128 Name = "llvm_cbe_" + VarName;
1129 } else {
1130 Name = Mang->getValueName(Operand);
1131 }
1132
1133 return Name;
1134}
1135
Chris Lattnerfda3b292002-08-19 21:32:41 +00001136void CWriter::writeOperandInternal(Value *Operand) {
Chris Lattnerf3a86f02002-08-19 23:09:46 +00001137 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnerfb70cf52003-06-17 04:39:14 +00001138 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Chris Lattnerf3a86f02002-08-19 23:09:46 +00001139 // Should we inline this instruction to build a tree?
Misha Brukman2b1e1002005-02-14 18:52:35 +00001140 Out << '(';
Chris Lattnerf3a86f02002-08-19 23:09:46 +00001141 visit(*I);
Misha Brukman2b1e1002005-02-14 18:52:35 +00001142 Out << ')';
Chris Lattnerf3a86f02002-08-19 23:09:46 +00001143 return;
1144 }
Misha Brukmanea548c02005-04-20 16:05:03 +00001145
Reid Spencercb3fb5d2004-07-18 00:44:37 +00001146 Constant* CPV = dyn_cast<Constant>(Operand);
Bill Wendling77a345f2007-02-23 22:45:08 +00001147
1148 if (CPV && !isa<GlobalValue>(CPV))
Misha Brukmanea548c02005-04-20 16:05:03 +00001149 printConstant(CPV);
Bill Wendling77a345f2007-02-23 22:45:08 +00001150 else
1151 Out << GetValueName(Operand);
Chris Lattnerd4c569c2002-05-09 21:18:38 +00001152}
1153
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00001154void CWriter::writeOperandRaw(Value *Operand) {
1155 Constant* CPV = dyn_cast<Constant>(Operand);
1156 if (CPV && !isa<GlobalValue>(CPV)) {
1157 printConstant(CPV);
1158 } else {
Bill Wendling77a345f2007-02-23 22:45:08 +00001159 Out << GetValueName(Operand);
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00001160 }
1161}
1162
Chris Lattnerf8b06682002-06-25 15:57:03 +00001163void CWriter::writeOperand(Value *Operand) {
Chris Lattnerfb70cf52003-06-17 04:39:14 +00001164 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001165 Out << "(&"; // Global variables are referenced as their addresses by llvm
Chris Lattnerd4c569c2002-05-09 21:18:38 +00001166
1167 writeOperandInternal(Operand);
Chris Lattner5d190e22002-05-09 20:53:56 +00001168
Chris Lattnerfb70cf52003-06-17 04:39:14 +00001169 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Misha Brukman2b1e1002005-02-14 18:52:35 +00001170 Out << ')';
Chris Lattner5d190e22002-05-09 20:53:56 +00001171}
1172
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001173// Some instructions need to have their result value casted back to the
1174// original types because their operands were casted to the expected type.
1175// This function takes care of detecting that case and printing the cast
1176// for the Instruction.
1177bool CWriter::writeInstructionCast(const Instruction &I) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001178 const Type *Ty = I.getOperand(0)->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001179 switch (I.getOpcode()) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001180 case Instruction::LShr:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001181 case Instruction::URem:
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001182 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00001183 Out << "((";
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001184 printSimpleType(Out, Ty, false);
Reid Spencer266e42b2006-12-23 06:05:41 +00001185 Out << ")(";
1186 return true;
Reid Spencerfdff9382006-11-08 06:47:33 +00001187 case Instruction::AShr:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001188 case Instruction::SRem:
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001189 case Instruction::SDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00001190 Out << "((";
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001191 printSimpleType(Out, Ty, true);
Reid Spencer266e42b2006-12-23 06:05:41 +00001192 Out << ")(";
1193 return true;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001194 default: break;
1195 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001196 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001197}
1198
1199// Write the operand with a cast to another type based on the Opcode being used.
1200// This will be used in cases where an instruction has specific type
1201// requirements (usually signedness) for its operands.
1202void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1203
1204 // Extract the operand's type, we'll need it.
1205 const Type* OpTy = Operand->getType();
1206
1207 // Indicate whether to do the cast or not.
1208 bool shouldCast = false;
1209
Reid Spencer266e42b2006-12-23 06:05:41 +00001210 // Indicate whether the cast should be to a signed type or not.
1211 bool castIsSigned = false;
1212
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001213 // Based on the Opcode for which this Operand is being written, determine
1214 // the new type to which the operand should be casted by setting the value
1215 // of OpTy. If we change OpTy, also set shouldCast to true.
1216 switch (Opcode) {
1217 default:
1218 // for most instructions, it doesn't matter
1219 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001220 case Instruction::LShr:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001221 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00001222 case Instruction::URem: // Cast to unsigned first
1223 shouldCast = true;
1224 castIsSigned = false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001225 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001226 case Instruction::AShr:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001227 case Instruction::SDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00001228 case Instruction::SRem: // Cast to signed first
1229 shouldCast = true;
1230 castIsSigned = true;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001231 break;
1232 }
1233
1234 // Write out the casted operand if we should, otherwise just write the
1235 // operand.
1236 if (shouldCast) {
1237 Out << "((";
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001238 printSimpleType(Out, OpTy, castIsSigned);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001239 Out << ")";
Chris Lattner4995f922007-05-03 02:57:13 +00001240 writeOperand(Operand);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001241 Out << ")";
1242 } else
1243 writeOperand(Operand);
Reid Spencer266e42b2006-12-23 06:05:41 +00001244}
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001245
Reid Spencer266e42b2006-12-23 06:05:41 +00001246// Write the operand with a cast to another type based on the icmp predicate
1247// being used.
1248void CWriter::writeOperandWithCast(Value* Operand, ICmpInst::Predicate predicate) {
1249
1250 // Extract the operand's type, we'll need it.
1251 const Type* OpTy = Operand->getType();
1252
1253 // Indicate whether to do the cast or not.
1254 bool shouldCast = false;
1255
1256 // Indicate whether the cast should be to a signed type or not.
1257 bool castIsSigned = false;
1258
1259 // Based on the Opcode for which this Operand is being written, determine
1260 // the new type to which the operand should be casted by setting the value
1261 // of OpTy. If we change OpTy, also set shouldCast to true.
1262 switch (predicate) {
1263 default:
1264 // for eq and ne, it doesn't matter
Chris Lattner4995f922007-05-03 02:57:13 +00001265 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00001266 case ICmpInst::ICMP_UGT:
1267 case ICmpInst::ICMP_UGE:
1268 case ICmpInst::ICMP_ULT:
1269 case ICmpInst::ICMP_ULE:
1270 shouldCast = true;
1271 break;
1272 case ICmpInst::ICMP_SGT:
1273 case ICmpInst::ICMP_SGE:
1274 case ICmpInst::ICMP_SLT:
1275 case ICmpInst::ICMP_SLE:
1276 shouldCast = true;
1277 castIsSigned = true;
1278 break;
1279 }
1280
1281 // Write out the casted operand if we should, otherwise just write the
1282 // operand.
1283 if (shouldCast) {
1284 Out << "((";
Chris Lattner03c49532007-01-15 02:27:26 +00001285 if (OpTy->isInteger() && OpTy != Type::Int1Ty)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001286 printSimpleType(Out, OpTy, castIsSigned);
Reid Spencer266e42b2006-12-23 06:05:41 +00001287 else
Reid Spencer1fc9be32007-01-09 17:09:09 +00001288 printType(Out, OpTy); // not integer, sign doesn't matter
Reid Spencer266e42b2006-12-23 06:05:41 +00001289 Out << ")";
Reid Spencer266e42b2006-12-23 06:05:41 +00001290 writeOperand(Operand);
Chris Lattner4995f922007-05-03 02:57:13 +00001291 Out << ")";
1292 } else
1293 writeOperand(Operand);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001294}
1295
Chris Lattnera80de5a2003-06-28 17:15:12 +00001296// generateCompilerSpecificCode - This is where we add conditional compilation
1297// directives to cater to specific compilers as need be.
1298//
Chris Lattner9005b802003-11-16 22:06:14 +00001299static void generateCompilerSpecificCode(std::ostream& Out) {
Chris Lattner207291f2006-03-07 22:58:23 +00001300 // Alloca is hard to get, and we don't want to include stdlib.h here.
Chris Lattnera80de5a2003-06-28 17:15:12 +00001301 Out << "/* get a declaration for alloca */\n"
Chris Lattner8fd10362006-06-02 18:54:01 +00001302 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
Anton Korobeynikov8b7aab02007-04-17 09:20:00 +00001303 << "#define alloca(x) __builtin_alloca((x))\n"
1304 << "#define _alloca(x) __builtin_alloca((x))\n"
Reid Spencerd5d45b82005-01-23 04:32:47 +00001305 << "#elif defined(__APPLE__)\n"
Joel Stanleye4902142003-02-12 20:45:00 +00001306 << "extern void *__builtin_alloca(unsigned long);\n"
1307 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00001308 << "#define longjmp _longjmp\n"
1309 << "#define setjmp _setjmp\n"
Brian Gaeke81c7fd22004-12-10 05:44:45 +00001310 << "#elif defined(__sun__)\n"
1311 << "#if defined(__sparcv9)\n"
1312 << "extern void *__builtin_alloca(unsigned long);\n"
1313 << "#else\n"
1314 << "extern void *__builtin_alloca(unsigned int);\n"
1315 << "#endif\n"
1316 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohene3955a02006-04-17 17:55:41 +00001317 << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
Chris Lattnere4c60eb2004-10-06 04:21:52 +00001318 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohencc560c92007-03-28 23:08:37 +00001319 << "#elif defined(_MSC_VER)\n"
Jeff Cohen68e93b72007-03-29 17:42:21 +00001320 << "#define inline _inline\n"
Jeff Cohencc560c92007-03-28 23:08:37 +00001321 << "#define alloca(x) _alloca(x)\n"
1322 << "#else\n"
Joel Stanleye4902142003-02-12 20:45:00 +00001323 << "#include <alloca.h>\n"
1324 << "#endif\n\n";
Chris Lattnera80de5a2003-06-28 17:15:12 +00001325
1326 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1327 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner27223932003-06-28 17:53:05 +00001328 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattnera80de5a2003-06-28 17:15:12 +00001329 << "#define __attribute__(X)\n"
Brian Gaekee869e0c2003-12-11 00:24:36 +00001330 << "#endif\n\n";
1331
Brian Gaekee869e0c2003-12-11 00:24:36 +00001332 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1333 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1334 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1335 << "#elif defined(__GNUC__)\n"
1336 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1337 << "#else\n"
1338 << "#define __EXTERNAL_WEAK__\n"
1339 << "#endif\n\n";
Brian Gaekee869e0c2003-12-11 00:24:36 +00001340
1341 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1342 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1343 << "#define __ATTRIBUTE_WEAK__\n"
1344 << "#elif defined(__GNUC__)\n"
1345 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1346 << "#else\n"
1347 << "#define __ATTRIBUTE_WEAK__\n"
1348 << "#endif\n\n";
Brian Gaeke1dde3fa2004-07-21 03:15:26 +00001349
Anton Korobeynikova0554d92007-01-12 19:20:47 +00001350 // Add hidden visibility support. FIXME: APPLE_CC?
1351 Out << "#if defined(__GNUC__)\n"
1352 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1353 << "#endif\n\n";
1354
Brian Gaeke1dde3fa2004-07-21 03:15:26 +00001355 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1356 // From the GCC documentation:
Misha Brukmanea548c02005-04-20 16:05:03 +00001357 //
Brian Gaeke1dde3fa2004-07-21 03:15:26 +00001358 // double __builtin_nan (const char *str)
1359 //
1360 // This is an implementation of the ISO C99 function nan.
1361 //
1362 // Since ISO C99 defines this function in terms of strtod, which we do
1363 // not implement, a description of the parsing is in order. The string is
1364 // parsed as by strtol; that is, the base is recognized by leading 0 or
1365 // 0x prefixes. The number parsed is placed in the significand such that
1366 // the least significant bit of the number is at the least significant
1367 // bit of the significand. The number is truncated to fit the significand
1368 // field provided. The significand is forced to be a quiet NaN.
1369 //
1370 // This function, if given a string literal, is evaluated early enough
1371 // that it is considered a compile-time constant.
1372 //
1373 // float __builtin_nanf (const char *str)
1374 //
1375 // Similar to __builtin_nan, except the return type is float.
1376 //
1377 // double __builtin_inf (void)
1378 //
1379 // Similar to __builtin_huge_val, except a warning is generated if the
1380 // target floating-point format does not support infinities. This
1381 // function is suitable for implementing the ISO C99 macro INFINITY.
1382 //
1383 // float __builtin_inff (void)
1384 //
1385 // Similar to __builtin_inf, except the return type is float.
1386 Out << "#ifdef __GNUC__\n"
Brian Gaeke35eb7ae2004-08-25 19:00:42 +00001387 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1388 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1389 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1390 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1391 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1392 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
Chris Lattnerd2d174d2006-02-13 22:22:42 +00001393 << "#define LLVM_PREFETCH(addr,rw,locality) "
1394 "__builtin_prefetch(addr,rw,locality)\n"
Chris Lattner207291f2006-03-07 22:58:23 +00001395 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1396 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
Chris Lattnerebb592b2006-07-28 20:58:47 +00001397 << "#define LLVM_ASM __asm__\n"
Brian Gaeke1dde3fa2004-07-21 03:15:26 +00001398 << "#else\n"
Brian Gaeke35eb7ae2004-08-25 19:00:42 +00001399 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1400 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1401 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1402 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1403 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1404 << "#define LLVM_INFF 0.0F /* Float */\n"
Chris Lattner18335f82005-05-06 06:58:42 +00001405 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
Chris Lattner207291f2006-03-07 22:58:23 +00001406 << "#define __ATTRIBUTE_CTOR__\n"
1407 << "#define __ATTRIBUTE_DTOR__\n"
Chris Lattnerebb592b2006-07-28 20:58:47 +00001408 << "#define LLVM_ASM(X)\n"
Chris Lattner18335f82005-05-06 06:58:42 +00001409 << "#endif\n\n";
Chris Lattner1904e452007-05-13 22:19:27 +00001410
1411 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1412 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1413 << "#define __builtin_stack_restore(X) /* noop */\n"
1414 << "#endif\n\n";
Chris Lattner18335f82005-05-06 06:58:42 +00001415
1416 // Output target-specific code that should be inserted into main.
1417 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1418 // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
1419 Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
Evan Cheng164a2212006-06-20 22:11:12 +00001420 << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
1421 << "defined(__x86_64__)\n"
Chris Lattner18335f82005-05-06 06:58:42 +00001422 << "#undef CODE_FOR_MAIN\n"
1423 << "#define CODE_FOR_MAIN() \\\n"
1424 << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
1425 << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
1426 << "#endif\n#endif\n";
1427
Joel Stanleye4902142003-02-12 20:45:00 +00001428}
1429
Chris Lattner207291f2006-03-07 22:58:23 +00001430/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1431/// the StaticTors set.
1432static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1433 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1434 if (!InitList) return;
1435
1436 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1437 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1438 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1439
1440 if (CS->getOperand(1)->isNullValue())
1441 return; // Found a null terminator, exit printing.
1442 Constant *FP = CS->getOperand(1);
1443 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001444 if (CE->isCast())
Chris Lattner207291f2006-03-07 22:58:23 +00001445 FP = CE->getOperand(0);
1446 if (Function *F = dyn_cast<Function>(FP))
1447 StaticTors.insert(F);
1448 }
1449}
1450
1451enum SpecialGlobalClass {
1452 NotSpecial = 0,
1453 GlobalCtors, GlobalDtors,
1454 NotPrinted
1455};
1456
1457/// getGlobalVariableClass - If this is a global that is specially recognized
1458/// by LLVM, return a code that indicates how we should handle it.
1459static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1460 // If this is a global ctors/dtors list, handle it now.
1461 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1462 if (GV->getName() == "llvm.global_ctors")
1463 return GlobalCtors;
1464 else if (GV->getName() == "llvm.global_dtors")
1465 return GlobalDtors;
1466 }
1467
1468 // Otherwise, it it is other metadata, don't print it. This catches things
1469 // like debug information.
1470 if (GV->getSection() == "llvm.metadata")
1471 return NotPrinted;
1472
1473 return NotSpecial;
1474}
1475
1476
Chris Lattnerd2b6e182004-02-13 23:00:29 +00001477bool CWriter::doInitialization(Module &M) {
1478 // Initialize
1479 TheModule = &M;
Chris Lattner14d328e2004-05-09 04:30:20 +00001480
Reid Spencer1e960cd2007-01-29 17:51:02 +00001481 TD = new TargetData(&M);
1482 IL = new IntrinsicLowering(*TD);
1483 IL->AddPrototypes(M);
Misha Brukmanea548c02005-04-20 16:05:03 +00001484
Chris Lattnerd2b6e182004-02-13 23:00:29 +00001485 // Ensure that all structure types have names...
Chris Lattnerd2b6e182004-02-13 23:00:29 +00001486 Mang = new Mangler(M);
Chris Lattner4b3b9192005-11-10 21:39:29 +00001487 Mang->markCharUnacceptable('.');
Chris Lattner9005b802003-11-16 22:06:14 +00001488
Chris Lattner207291f2006-03-07 22:58:23 +00001489 // Keep track of which functions are static ctors/dtors so they can have
1490 // an attribute added to their prototypes.
1491 std::set<Function*> StaticCtors, StaticDtors;
1492 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1493 I != E; ++I) {
1494 switch (getGlobalVariableClass(I)) {
1495 default: break;
1496 case GlobalCtors:
1497 FindStaticTors(I, StaticCtors);
1498 break;
1499 case GlobalDtors:
1500 FindStaticTors(I, StaticDtors);
1501 break;
1502 }
1503 }
1504
Chris Lattnereabc6472002-05-09 02:28:59 +00001505 // get declaration for alloca
Joel Stanleye4902142003-02-12 20:45:00 +00001506 Out << "/* Provide Declarations */\n";
Chris Lattner9005b802003-11-16 22:06:14 +00001507 Out << "#include <stdarg.h>\n"; // Varargs support
1508 Out << "#include <setjmp.h>\n"; // Unwind support
Chris Lattnera80de5a2003-06-28 17:15:12 +00001509 generateCompilerSpecificCode(Out);
Chris Lattner9005b802003-11-16 22:06:14 +00001510
Chris Lattner239ff502003-06-02 03:10:53 +00001511 // Provide a definition for `bool' if not compiling with a C++ compiler.
1512 Out << "\n"
Vikram S. Adve8a5c9b12002-08-25 20:00:08 +00001513 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmanea548c02005-04-20 16:05:03 +00001514
Chris Lattner230d8322002-09-20 23:26:33 +00001515 << "\n\n/* Support for floating point constants */\n"
1516 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnercffe4172002-11-07 19:43:59 +00001517 << "typedef unsigned int ConstantFloatTy;\n"
Misha Brukmanea548c02005-04-20 16:05:03 +00001518
Chris Lattnerb5815272002-08-19 21:48:40 +00001519 << "\n\n/* Global Declarations */\n";
1520
1521 // First output all the declarations for the program, because C requires
1522 // Functions & globals to be declared before they are used.
1523 //
Chris Lattnereabc6472002-05-09 02:28:59 +00001524
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00001525 // Loop over the symbol table, emitting all named constants...
Reid Spencer32af9e82007-01-06 07:24:44 +00001526 printModuleTypes(M.getTypeSymbolTable());
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00001527
Chris Lattnerb5815272002-08-19 21:48:40 +00001528 // Global variable declarations...
Chris Lattner531f9e92005-03-15 04:54:21 +00001529 if (!M.global_empty()) {
Vikram S. Adve9d0fb1a2002-09-17 11:50:38 +00001530 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnerd2d174d2006-02-13 22:22:42 +00001531 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1532 I != E; ++I) {
Lauro Ramos Venancioe6818b22007-04-12 18:42:08 +00001533
1534 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage())
Vikram S. Adve9d0fb1a2002-09-17 11:50:38 +00001535 Out << "extern ";
Lauro Ramos Venancioe6818b22007-04-12 18:42:08 +00001536 else if (I->hasDLLImportLinkage())
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +00001537 Out << "__declspec(dllimport) ";
Lauro Ramos Venancioe6818b22007-04-12 18:42:08 +00001538 else
1539 continue; // Internal Global
1540
1541 // Thread Local Storage
1542 if (I->isThreadLocal())
1543 Out << "__thread ";
1544
1545 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1546
1547 if (I->hasExternalWeakLinkage())
1548 Out << " __EXTERNAL_WEAK__";
1549 Out << ";\n";
Chris Lattner132ba2a2002-05-09 15:18:52 +00001550 }
Chris Lattner132ba2a2002-05-09 15:18:52 +00001551 }
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00001552
Chris Lattnerb5815272002-08-19 21:48:40 +00001553 // Function declarations
Chris Lattner207291f2006-03-07 22:58:23 +00001554 Out << "\n/* Function Declarations */\n";
Chris Lattner9c0a2432005-08-23 20:22:50 +00001555 Out << "double fmod(double, double);\n"; // Support for FP rem
1556 Out << "float fmodf(float, float);\n";
1557
Chris Lattner207291f2006-03-07 22:58:23 +00001558 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1559 // Don't print declarations for intrinsic functions.
Reid Spenceraa1c6142006-10-22 09:58:21 +00001560 if (!I->getIntrinsicID() && I->getName() != "setjmp" &&
1561 I->getName() != "longjmp" && I->getName() != "_setjmp") {
Anton Korobeynikov12c94942006-12-01 00:25:12 +00001562 if (I->hasExternalWeakLinkage())
1563 Out << "extern ";
Chris Lattner207291f2006-03-07 22:58:23 +00001564 printFunctionSignature(I, true);
1565 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1566 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov12c94942006-12-01 00:25:12 +00001567 if (I->hasExternalWeakLinkage())
1568 Out << " __EXTERNAL_WEAK__";
Chris Lattner207291f2006-03-07 22:58:23 +00001569 if (StaticCtors.count(I))
1570 Out << " __ATTRIBUTE_CTOR__";
1571 if (StaticDtors.count(I))
1572 Out << " __ATTRIBUTE_DTOR__";
Anton Korobeynikova0554d92007-01-12 19:20:47 +00001573 if (I->hasHiddenVisibility())
1574 Out << " __HIDDEN__";
Chris Lattnerebb592b2006-07-28 20:58:47 +00001575
1576 if (I->hasName() && I->getName()[0] == 1)
1577 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1578
Chris Lattner207291f2006-03-07 22:58:23 +00001579 Out << ";\n";
Chris Lattner7934dad2002-08-20 16:55:48 +00001580 }
Chris Lattnerb5815272002-08-19 21:48:40 +00001581 }
1582
Joel Stanleyfbb9ab42003-06-25 04:52:09 +00001583 // Output the global variable declarations
Chris Lattner531f9e92005-03-15 04:54:21 +00001584 if (!M.global_empty()) {
Joel Stanleyfbb9ab42003-06-25 04:52:09 +00001585 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerd2d174d2006-02-13 22:22:42 +00001586 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1587 I != E; ++I)
Reid Spencer5301e7c2007-01-30 20:08:39 +00001588 if (!I->isDeclaration()) {
Chris Lattner207291f2006-03-07 22:58:23 +00001589 // Ignore special globals, such as debug info.
1590 if (getGlobalVariableClass(I))
1591 continue;
Lauro Ramos Venancioe6818b22007-04-12 18:42:08 +00001592
Chris Lattner26d9c222004-12-03 17:19:10 +00001593 if (I->hasInternalLinkage())
1594 Out << "static ";
1595 else
1596 Out << "extern ";
Lauro Ramos Venancioe6818b22007-04-12 18:42:08 +00001597
1598 // Thread Local Storage
1599 if (I->isThreadLocal())
1600 Out << "__thread ";
1601
Reid Spencer1fc9be32007-01-09 17:09:09 +00001602 printType(Out, I->getType()->getElementType(), false,
Bill Wendling77a345f2007-02-23 22:45:08 +00001603 GetValueName(I));
Chris Lattnere4e25952003-11-03 17:32:38 +00001604
1605 if (I->hasLinkOnceLinkage())
1606 Out << " __attribute__((common))";
1607 else if (I->hasWeakLinkage())
Brian Gaekee869e0c2003-12-11 00:24:36 +00001608 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov12c94942006-12-01 00:25:12 +00001609 else if (I->hasExternalWeakLinkage())
1610 Out << " __EXTERNAL_WEAK__";
Anton Korobeynikova0554d92007-01-12 19:20:47 +00001611 if (I->hasHiddenVisibility())
1612 Out << " __HIDDEN__";
Nick Hildenbrandtc7147032002-10-28 19:05:12 +00001613 Out << ";\n";
1614 }
1615 }
1616
Vikram S. Adve9d0fb1a2002-09-17 11:50:38 +00001617 // Output the global variable definitions and contents...
Chris Lattner531f9e92005-03-15 04:54:21 +00001618 if (!M.global_empty()) {
Vikram S. Adve9d0fb1a2002-09-17 11:50:38 +00001619 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Chris Lattnerd2d174d2006-02-13 22:22:42 +00001620 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1621 I != E; ++I)
Reid Spencer5301e7c2007-01-30 20:08:39 +00001622 if (!I->isDeclaration()) {
Chris Lattner207291f2006-03-07 22:58:23 +00001623 // Ignore special globals, such as debug info.
1624 if (getGlobalVariableClass(I))
1625 continue;
Lauro Ramos Venancioe6818b22007-04-12 18:42:08 +00001626
Chris Lattner8fad3ea2002-10-16 20:08:47 +00001627 if (I->hasInternalLinkage())
1628 Out << "static ";
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +00001629 else if (I->hasDLLImportLinkage())
1630 Out << "__declspec(dllimport) ";
1631 else if (I->hasDLLExportLinkage())
1632 Out << "__declspec(dllexport) ";
Lauro Ramos Venancioe6818b22007-04-12 18:42:08 +00001633
1634 // Thread Local Storage
1635 if (I->isThreadLocal())
1636 Out << "__thread ";
1637
Reid Spencer1fc9be32007-01-09 17:09:09 +00001638 printType(Out, I->getType()->getElementType(), false,
Bill Wendling77a345f2007-02-23 22:45:08 +00001639 GetValueName(I));
Chris Lattner90921a72003-06-28 17:08:36 +00001640 if (I->hasLinkOnceLinkage())
1641 Out << " __attribute__((common))";
Chris Lattner068ad842003-10-16 18:29:00 +00001642 else if (I->hasWeakLinkage())
Brian Gaekee869e0c2003-12-11 00:24:36 +00001643 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner39c0a192003-11-03 17:35:00 +00001644
Anton Korobeynikova0554d92007-01-12 19:20:47 +00001645 if (I->hasHiddenVisibility())
1646 Out << " __HIDDEN__";
1647
Chris Lattner39c0a192003-11-03 17:35:00 +00001648 // If the initializer is not null, emit the initializer. If it is null,
1649 // we try to avoid emitting large amounts of zeros. The problem with
1650 // this, however, occurs when the variable has weak linkage. In this
1651 // case, the assembler will complain about the variable being both weak
1652 // and common, so we disable this optimization.
Chris Lattner73ffc882004-02-20 05:49:22 +00001653 if (!I->getInitializer()->isNullValue()) {
Chris Lattnerb630abf2003-06-06 07:10:24 +00001654 Out << " = " ;
1655 writeOperand(I->getInitializer());
Chris Lattner73ffc882004-02-20 05:49:22 +00001656 } else if (I->hasWeakLinkage()) {
1657 // We have to specify an initializer, but it doesn't have to be
1658 // complete. If the value is an aggregate, print out { 0 }, and let
1659 // the compiler figure out the rest of the zeros.
1660 Out << " = " ;
1661 if (isa<StructType>(I->getInitializer()->getType()) ||
Robert Bocchino4b41c8e2006-01-20 20:43:57 +00001662 isa<ArrayType>(I->getInitializer()->getType()) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00001663 isa<VectorType>(I->getInitializer()->getType())) {
Chris Lattner73ffc882004-02-20 05:49:22 +00001664 Out << "{ 0 }";
1665 } else {
1666 // Just print it out normally.
1667 writeOperand(I->getInitializer());
1668 }
Chris Lattnerb630abf2003-06-06 07:10:24 +00001669 }
Chris Lattner8fad3ea2002-10-16 20:08:47 +00001670 Out << ";\n";
Chris Lattnerb5815272002-08-19 21:48:40 +00001671 }
Chris Lattnerb5815272002-08-19 21:48:40 +00001672 }
1673
Chris Lattnerd2b6e182004-02-13 23:00:29 +00001674 if (!M.empty())
Chris Lattnerb5815272002-08-19 21:48:40 +00001675 Out << "\n\n/* Function Bodies */\n";
Reid Spencer13cae7c2007-01-08 06:58:32 +00001676
1677 // Emit some helper functions for dealing with FCMP instruction's
1678 // predicates
1679 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
1680 Out << "return X == X && Y == Y; }\n";
1681 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
1682 Out << "return X != X || Y != Y; }\n";
1683 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
Reid Spencerc0b86d52007-01-08 08:00:00 +00001684 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencer13cae7c2007-01-08 06:58:32 +00001685 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
Reid Spencerc0b86d52007-01-08 08:00:00 +00001686 Out << "return X != Y; }\n";
Reid Spencer13cae7c2007-01-08 06:58:32 +00001687 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
Reid Spencerc0b86d52007-01-08 08:00:00 +00001688 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencer13cae7c2007-01-08 06:58:32 +00001689 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
Reid Spencerc0b86d52007-01-08 08:00:00 +00001690 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencer13cae7c2007-01-08 06:58:32 +00001691 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
Reid Spencerc0b86d52007-01-08 08:00:00 +00001692 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencer13cae7c2007-01-08 06:58:32 +00001693 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
Reid Spencerc0b86d52007-01-08 08:00:00 +00001694 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencer13cae7c2007-01-08 06:58:32 +00001695 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
Reid Spencerc0b86d52007-01-08 08:00:00 +00001696 Out << "return X == Y ; }\n";
Reid Spencer13cae7c2007-01-08 06:58:32 +00001697 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
Reid Spencerc0b86d52007-01-08 08:00:00 +00001698 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
Reid Spencer13cae7c2007-01-08 06:58:32 +00001699 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
Reid Spencerc0b86d52007-01-08 08:00:00 +00001700 Out << "return X < Y ; }\n";
Reid Spencer13cae7c2007-01-08 06:58:32 +00001701 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
Reid Spencerc0b86d52007-01-08 08:00:00 +00001702 Out << "return X > Y ; }\n";
Reid Spencer13cae7c2007-01-08 06:58:32 +00001703 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
Reid Spencerc0b86d52007-01-08 08:00:00 +00001704 Out << "return X <= Y ; }\n";
Reid Spencer13cae7c2007-01-08 06:58:32 +00001705 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
Reid Spencerc0b86d52007-01-08 08:00:00 +00001706 Out << "return X >= Y ; }\n";
Chris Lattnerd2b6e182004-02-13 23:00:29 +00001707 return false;
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00001708}
1709
Chris Lattnerd2b6e182004-02-13 23:00:29 +00001710
Chris Lattner5d841b22003-10-12 04:36:29 +00001711/// Output all floating point constants that cannot be printed accurately...
Chris Lattner9c299912004-05-09 06:20:51 +00001712void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner5d841b22003-10-12 04:36:29 +00001713 // Scan the module for floating point constants. If any FP constant is used
1714 // in the function, we want to redirect it here so that we do not depend on
1715 // the precision of the printed form, unless the printed form preserves
1716 // precision.
1717 //
Chris Lattner9c299912004-05-09 06:20:51 +00001718 static unsigned FPCounter = 0;
1719 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1720 I != E; ++I)
1721 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1722 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1723 !FPConstantMap.count(FPC)) {
Chris Lattner9c299912004-05-09 06:20:51 +00001724 FPConstantMap[FPC] = FPCounter; // Number the FP constants
Misha Brukmanea548c02005-04-20 16:05:03 +00001725
Chris Lattner9c299912004-05-09 06:20:51 +00001726 if (FPC->getType() == Type::DoubleTy) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001727 double Val = FPC->getValueAPF().convertToDouble();
Chris Lattner9c299912004-05-09 06:20:51 +00001728 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
Jim Laskeyb74c6662005-08-17 19:34:49 +00001729 << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
Chris Lattner9c299912004-05-09 06:20:51 +00001730 << "ULL; /* " << Val << " */\n";
1731 } else if (FPC->getType() == Type::FloatTy) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001732 float Val = FPC->getValueAPF().convertToFloat();
Chris Lattner9c299912004-05-09 06:20:51 +00001733 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
Jim Laskeyb74c6662005-08-17 19:34:49 +00001734 << " = 0x" << std::hex << FloatToBits(Val) << std::dec
Chris Lattner9c299912004-05-09 06:20:51 +00001735 << "U; /* " << Val << " */\n";
1736 } else
1737 assert(0 && "Unknown float type!");
1738 }
Misha Brukmanea548c02005-04-20 16:05:03 +00001739
Misha Brukman2b1e1002005-02-14 18:52:35 +00001740 Out << '\n';
Chris Lattner9c299912004-05-09 06:20:51 +00001741}
Chris Lattner5d841b22003-10-12 04:36:29 +00001742
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00001743
Chris Lattner32d812f2002-09-20 15:12:13 +00001744/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchino4b41c8e2006-01-20 20:43:57 +00001745/// type name is found, emit its declaration...
Chris Lattner37bd1172002-09-20 14:56:54 +00001746///
Reid Spencer32af9e82007-01-06 07:24:44 +00001747void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
Reid Spencerb9435552006-12-11 20:39:15 +00001748 Out << "/* Helper union for bitcasts */\n";
1749 Out << "typedef union {\n";
Reid Spencere63b6512006-12-31 05:55:36 +00001750 Out << " unsigned int Int32;\n";
1751 Out << " unsigned long long Int64;\n";
Reid Spencer20753742006-12-12 00:11:08 +00001752 Out << " float Float;\n";
1753 Out << " double Double;\n";
Reid Spencerb9435552006-12-11 20:39:15 +00001754 Out << "} llvmBitCastUnion;\n";
1755
Chris Lattnerc9b09842005-03-06 02:28:23 +00001756 // We are only interested in the type plane of the symbol table.
Reid Spencer32af9e82007-01-06 07:24:44 +00001757 TypeSymbolTable::const_iterator I = TST.begin();
1758 TypeSymbolTable::const_iterator End = TST.end();
Chris Lattnerc9b09842005-03-06 02:28:23 +00001759
1760 // If there are no type names, exit early.
1761 if (I == End) return;
Misha Brukmanea548c02005-04-20 16:05:03 +00001762
Chris Lattner7bd37ed2002-09-20 15:18:30 +00001763 // Print out forward declarations for structure types before anything else!
1764 Out << "/* Structure forward decls */\n";
Chris Lattner4202f372007-01-16 18:02:45 +00001765 for (; I != End; ++I) {
1766 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1767 Out << Name << ";\n";
1768 TypeNames.insert(std::make_pair(I->second, Name));
1769 }
Chris Lattner7bd37ed2002-09-20 15:18:30 +00001770
Misha Brukman2b1e1002005-02-14 18:52:35 +00001771 Out << '\n';
Chris Lattner7bd37ed2002-09-20 15:18:30 +00001772
Chris Lattner5488ade2007-01-16 07:22:23 +00001773 // Now we can print out typedefs. Above, we guaranteed that this can only be
Chris Lattner4202f372007-01-16 18:02:45 +00001774 // for struct or opaque types.
Chris Lattner7bd37ed2002-09-20 15:18:30 +00001775 Out << "/* Typedefs */\n";
Reid Spencer32af9e82007-01-06 07:24:44 +00001776 for (I = TST.begin(); I != End; ++I) {
Chris Lattner369b61f2005-11-10 18:53:25 +00001777 std::string Name = "l_" + Mang->makeNameProper(I->first);
Chris Lattner9c299912004-05-09 06:20:51 +00001778 Out << "typedef ";
Chris Lattner4202f372007-01-16 18:02:45 +00001779 printType(Out, I->second, false, Name);
Chris Lattner9c299912004-05-09 06:20:51 +00001780 Out << ";\n";
1781 }
Misha Brukmanea548c02005-04-20 16:05:03 +00001782
Misha Brukman2b1e1002005-02-14 18:52:35 +00001783 Out << '\n';
Chris Lattnereed155e2002-05-09 14:40:11 +00001784
Chris Lattner9a973b42002-09-20 15:05:40 +00001785 // Keep track of which structures have been printed so far...
1786 std::set<const StructType *> StructPrinted;
1787
Nick Hildenbrandte89a6eb2002-09-14 21:36:24 +00001788 // Loop over all structures then push them into the stack so they are
1789 // printed in the correct order.
Chris Lattner32d812f2002-09-20 15:12:13 +00001790 //
Chris Lattner7bd37ed2002-09-20 15:18:30 +00001791 Out << "/* Structure contents */\n";
Reid Spencer32af9e82007-01-06 07:24:44 +00001792 for (I = TST.begin(); I != End; ++I)
Chris Lattner32d812f2002-09-20 15:12:13 +00001793 if (const StructType *STy = dyn_cast<StructType>(I->second))
Chris Lattner4fa54562003-11-02 01:29:27 +00001794 // Only print out used types!
Chris Lattner9c299912004-05-09 06:20:51 +00001795 printContainedStructs(STy, StructPrinted);
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00001796}
1797
Nick Hildenbrandte89a6eb2002-09-14 21:36:24 +00001798// Push the struct onto the stack and recursively push all structs
1799// this one depends on.
Robert Bocchino4b41c8e2006-01-20 20:43:57 +00001800//
Reid Spencer09575ba2007-02-15 03:39:18 +00001801// TODO: Make this work properly with vector types
Robert Bocchino4b41c8e2006-01-20 20:43:57 +00001802//
Chris Lattner9a973b42002-09-20 15:05:40 +00001803void CWriter::printContainedStructs(const Type *Ty,
1804 std::set<const StructType*> &StructPrinted){
Chris Lattnereca87342006-01-20 18:57:03 +00001805 // Don't walk through pointers.
Chris Lattner03c49532007-01-15 02:27:26 +00001806 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
Chris Lattnereca87342006-01-20 18:57:03 +00001807
1808 // Print all contained types first.
1809 for (Type::subtype_iterator I = Ty->subtype_begin(),
1810 E = Ty->subtype_end(); I != E; ++I)
1811 printContainedStructs(*I, StructPrinted);
1812
Misha Brukman1194d542003-07-09 17:33:50 +00001813 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattnereca87342006-01-20 18:57:03 +00001814 // Check to see if we have already printed this struct.
1815 if (StructPrinted.insert(STy).second) {
1816 // Print structure type out.
Misha Brukmanea548c02005-04-20 16:05:03 +00001817 std::string Name = TypeNames[STy];
Reid Spencer1fc9be32007-01-09 17:09:09 +00001818 printType(Out, STy, false, Name, true);
Chris Lattner7bd37ed2002-09-20 15:18:30 +00001819 Out << ";\n\n";
Nick Hildenbrandte89a6eb2002-09-14 21:36:24 +00001820 }
Nick Hildenbrandte89a6eb2002-09-14 21:36:24 +00001821 }
1822}
1823
Chris Lattner7934dad2002-08-20 16:55:48 +00001824void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00001825 /// isStructReturn - Should this function actually return a struct by-value?
1826 bool isStructReturn = F->getFunctionType()->isStructReturn();
Chris Lattnerde177e02006-05-23 23:39:48 +00001827
Joel Stanleyfbb9ab42003-06-25 04:52:09 +00001828 if (F->hasInternalLinkage()) Out << "static ";
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +00001829 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1830 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
Anton Korobeynikov6f7072c2006-09-17 20:25:45 +00001831 switch (F->getCallingConv()) {
1832 case CallingConv::X86_StdCall:
1833 Out << "__stdcall ";
1834 break;
1835 case CallingConv::X86_FastCall:
1836 Out << "__fastcall ";
1837 break;
1838 }
1839
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00001840 // Loop over the arguments, printing them...
Chris Lattnereabc6472002-05-09 02:28:59 +00001841 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Reid Spencer71b79e32007-04-09 06:17:21 +00001842 const ParamAttrsList *Attrs = FT->getParamAttrs();
Misha Brukmanea548c02005-04-20 16:05:03 +00001843
1844 std::stringstream FunctionInnards;
1845
Nick Hildenbrandtcdf2a182002-11-18 20:55:50 +00001846 // Print out the name...
Bill Wendling77a345f2007-02-23 22:45:08 +00001847 FunctionInnards << GetValueName(F) << '(';
Misha Brukmanea548c02005-04-20 16:05:03 +00001848
Chris Lattnerde177e02006-05-23 23:39:48 +00001849 bool PrintedArg = false;
Reid Spencer5301e7c2007-01-30 20:08:39 +00001850 if (!F->isDeclaration()) {
Chris Lattner531f9e92005-03-15 04:54:21 +00001851 if (!F->arg_empty()) {
Chris Lattnerde177e02006-05-23 23:39:48 +00001852 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1853
1854 // If this is a struct-return function, don't print the hidden
1855 // struct-return argument.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00001856 if (isStructReturn) {
Chris Lattnerde177e02006-05-23 23:39:48 +00001857 assert(I != E && "Invalid struct return function!");
1858 ++I;
1859 }
1860
Chris Lattner57ebe402003-05-03 03:14:35 +00001861 std::string ArgName;
Reid Spencerdf7c61d2007-01-07 03:24:48 +00001862 unsigned Idx = 1;
Chris Lattnerde177e02006-05-23 23:39:48 +00001863 for (; I != E; ++I) {
1864 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner7934dad2002-08-20 16:55:48 +00001865 if (I->hasName() || !Prototype)
Bill Wendling77a345f2007-02-23 22:45:08 +00001866 ArgName = GetValueName(I);
Misha Brukmanea548c02005-04-20 16:05:03 +00001867 else
Chris Lattner7934dad2002-08-20 16:55:48 +00001868 ArgName = "";
Reid Spencerdf7c61d2007-01-07 03:24:48 +00001869 printType(FunctionInnards, I->getType(),
Reid Spencera472f662007-04-11 02:44:20 +00001870 /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt),
Reid Spencerdf7c61d2007-01-07 03:24:48 +00001871 ArgName);
Chris Lattnerde177e02006-05-23 23:39:48 +00001872 PrintedArg = true;
Reid Spencerdf7c61d2007-01-07 03:24:48 +00001873 ++Idx;
Chris Lattner132ba2a2002-05-09 15:18:52 +00001874 }
1875 }
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00001876 } else {
Chris Lattnerde177e02006-05-23 23:39:48 +00001877 // Loop over the arguments, printing them.
1878 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1879
1880 // If this is a struct-return function, don't print the hidden
1881 // struct-return argument.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00001882 if (isStructReturn) {
Chris Lattnerde177e02006-05-23 23:39:48 +00001883 assert(I != E && "Invalid struct return function!");
1884 ++I;
1885 }
1886
Reid Spencerdf7c61d2007-01-07 03:24:48 +00001887 unsigned Idx = 1;
Chris Lattnerde177e02006-05-23 23:39:48 +00001888 for (; I != E; ++I) {
1889 if (PrintedArg) FunctionInnards << ", ";
Reid Spencerdf7c61d2007-01-07 03:24:48 +00001890 printType(FunctionInnards, *I,
Reid Spencera472f662007-04-11 02:44:20 +00001891 /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt));
Chris Lattnerde177e02006-05-23 23:39:48 +00001892 PrintedArg = true;
Reid Spencerdf7c61d2007-01-07 03:24:48 +00001893 ++Idx;
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00001894 }
1895 }
1896
Chris Lattner79ea4c42002-09-20 22:32:30 +00001897 // Finish printing arguments... if this is a vararg function, print the ...,
1898 // unless there are no known types, in which case, we just emit ().
1899 //
Chris Lattnerde177e02006-05-23 23:39:48 +00001900 if (FT->isVarArg() && PrintedArg) {
1901 if (PrintedArg) FunctionInnards << ", ";
Joel Stanleyfbb9ab42003-06-25 04:52:09 +00001902 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattnerde177e02006-05-23 23:39:48 +00001903 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattnereb64b6a2003-11-26 00:09:17 +00001904 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00001905 }
Misha Brukman2b1e1002005-02-14 18:52:35 +00001906 FunctionInnards << ')';
Chris Lattnerde177e02006-05-23 23:39:48 +00001907
1908 // Get the return tpe for the function.
1909 const Type *RetTy;
Anton Korobeynikov037c8672007-01-28 13:31:35 +00001910 if (!isStructReturn)
Chris Lattnerde177e02006-05-23 23:39:48 +00001911 RetTy = F->getReturnType();
1912 else {
1913 // If this is a struct-return function, print the struct-return type.
1914 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1915 }
1916
1917 // Print out the return type and the signature built above.
Reid Spencerbf38bf72007-01-09 06:38:06 +00001918 printType(Out, RetTy,
Reid Spencera472f662007-04-11 02:44:20 +00001919 /*isSigned=*/ Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
Reid Spencerdf7c61d2007-01-07 03:24:48 +00001920 FunctionInnards.str());
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00001921}
1922
Reid Spencer8bd63172006-12-17 20:24:50 +00001923static inline bool isFPIntBitCast(const Instruction &I) {
1924 if (!isa<BitCastInst>(I))
1925 return false;
1926 const Type *SrcTy = I.getOperand(0)->getType();
1927 const Type *DstTy = I.getType();
Chris Lattner03c49532007-01-15 02:27:26 +00001928 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
1929 (DstTy->isFloatingPoint() && SrcTy->isInteger());
Reid Spencer8bd63172006-12-17 20:24:50 +00001930}
1931
Chris Lattnerd2b6e182004-02-13 23:00:29 +00001932void CWriter::printFunction(Function &F) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00001933 /// isStructReturn - Should this function actually return a struct by-value?
1934 bool isStructReturn = F.getFunctionType()->isStructReturn();
1935
Chris Lattnerd2b6e182004-02-13 23:00:29 +00001936 printFunctionSignature(&F, false);
Chris Lattner4933e7e2002-05-09 15:49:41 +00001937 Out << " {\n";
Chris Lattnerde177e02006-05-23 23:39:48 +00001938
1939 // If this is a struct return function, handle the result with magic.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00001940 if (isStructReturn) {
Chris Lattnerde177e02006-05-23 23:39:48 +00001941 const Type *StructTy =
1942 cast<PointerType>(F.arg_begin()->getType())->getElementType();
1943 Out << " ";
Reid Spencer1fc9be32007-01-09 17:09:09 +00001944 printType(Out, StructTy, false, "StructReturn");
Chris Lattnerde177e02006-05-23 23:39:48 +00001945 Out << "; /* Struct return temporary */\n";
Chris Lattner4933e7e2002-05-09 15:49:41 +00001946
Chris Lattnerde177e02006-05-23 23:39:48 +00001947 Out << " ";
Reid Spencer1fc9be32007-01-09 17:09:09 +00001948 printType(Out, F.arg_begin()->getType(), false,
Bill Wendling77a345f2007-02-23 22:45:08 +00001949 GetValueName(F.arg_begin()));
Chris Lattnerde177e02006-05-23 23:39:48 +00001950 Out << " = &StructReturn;\n";
1951 }
1952
1953 bool PrintedVar = false;
1954
Chris Lattner2051c062002-05-09 20:39:03 +00001955 // print local variable information for the function
Reid Spencer174dc2f2006-12-17 18:50:51 +00001956 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
Chris Lattner2d3a7a62004-04-27 15:13:33 +00001957 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnerfb70cf52003-06-17 04:39:14 +00001958 Out << " ";
Bill Wendling77a345f2007-02-23 22:45:08 +00001959 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
Misha Brukman8dfa2e42005-01-31 06:19:57 +00001960 Out << "; /* Address-exposed local */\n";
Chris Lattnerde177e02006-05-23 23:39:48 +00001961 PrintedVar = true;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00001962 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
Chris Lattnereabc6472002-05-09 02:28:59 +00001963 Out << " ";
Bill Wendling77a345f2007-02-23 22:45:08 +00001964 printType(Out, I->getType(), false, GetValueName(&*I));
Chris Lattnereabc6472002-05-09 02:28:59 +00001965 Out << ";\n";
Misha Brukmanea548c02005-04-20 16:05:03 +00001966
Chris Lattner5b5c7932003-05-03 07:11:00 +00001967 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1968 Out << " ";
Reid Spencer1fc9be32007-01-09 17:09:09 +00001969 printType(Out, I->getType(), false,
Bill Wendling77a345f2007-02-23 22:45:08 +00001970 GetValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner5b5c7932003-05-03 07:11:00 +00001971 Out << ";\n";
1972 }
Chris Lattnerde177e02006-05-23 23:39:48 +00001973 PrintedVar = true;
Reid Spencer174dc2f2006-12-17 18:50:51 +00001974 }
1975 // We need a temporary for the BitCast to use so it can pluck a value out
Reid Spencer266e42b2006-12-23 06:05:41 +00001976 // of a union to do the BitCast. This is separate from the need for a
Reid Spencer174dc2f2006-12-17 18:50:51 +00001977 // variable to hold the result of the BitCast.
Reid Spencer8bd63172006-12-17 20:24:50 +00001978 if (isFPIntBitCast(*I)) {
Bill Wendling77a345f2007-02-23 22:45:08 +00001979 Out << " llvmBitCastUnion " << GetValueName(&*I)
Reid Spencerb9435552006-12-11 20:39:15 +00001980 << "__BITCAST_TEMPORARY;\n";
Reid Spencer174dc2f2006-12-17 18:50:51 +00001981 PrintedVar = true;
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00001982 }
Reid Spencer174dc2f2006-12-17 18:50:51 +00001983 }
Chris Lattner230d8322002-09-20 23:26:33 +00001984
Chris Lattnerde177e02006-05-23 23:39:48 +00001985 if (PrintedVar)
1986 Out << '\n';
Chris Lattner230d8322002-09-20 23:26:33 +00001987
Chris Lattnerb3b1c272004-12-13 21:52:52 +00001988 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner18335f82005-05-06 06:58:42 +00001989 Out << " CODE_FOR_MAIN();\n";
Chris Lattnerb3b1c272004-12-13 21:52:52 +00001990
Chris Lattnereabc6472002-05-09 02:28:59 +00001991 // print the basic blocks
Chris Lattnerd2b6e182004-02-13 23:00:29 +00001992 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnerf719a522004-05-09 20:41:32 +00001993 if (Loop *L = LI->getLoopFor(BB)) {
1994 if (L->getHeader() == BB && L->getParentLoop() == 0)
1995 printLoop(L);
1996 } else {
1997 printBasicBlock(BB);
Chris Lattnerd4c569c2002-05-09 21:18:38 +00001998 }
Chris Lattner4933e7e2002-05-09 15:49:41 +00001999 }
Misha Brukmanea548c02005-04-20 16:05:03 +00002000
Chris Lattner4933e7e2002-05-09 15:49:41 +00002001 Out << "}\n\n";
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00002002}
2003
Chris Lattnerf719a522004-05-09 20:41:32 +00002004void CWriter::printLoop(Loop *L) {
2005 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2006 << "' to make GCC happy */\n";
2007 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2008 BasicBlock *BB = L->getBlocks()[i];
2009 Loop *BBLoop = LI->getLoopFor(BB);
2010 if (BBLoop == L)
2011 printBasicBlock(BB);
2012 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmanea548c02005-04-20 16:05:03 +00002013 printLoop(BBLoop);
Chris Lattnerf719a522004-05-09 20:41:32 +00002014 }
2015 Out << " } while (1); /* end of syntactic loop '"
2016 << L->getHeader()->getName() << "' */\n";
2017}
2018
2019void CWriter::printBasicBlock(BasicBlock *BB) {
2020
2021 // Don't print the label for the basic block if there are no uses, or if
2022 // the only terminator use is the predecessor basic block's terminator.
2023 // We have to scan the use list because PHI nodes use basic blocks too but
2024 // do not require a label to be generated.
2025 //
2026 bool NeedsLabel = false;
2027 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2028 if (isGotoCodeNecessary(*PI, BB)) {
2029 NeedsLabel = true;
2030 break;
2031 }
Misha Brukmanea548c02005-04-20 16:05:03 +00002032
Bill Wendling77a345f2007-02-23 22:45:08 +00002033 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
Misha Brukmanea548c02005-04-20 16:05:03 +00002034
Chris Lattnerf719a522004-05-09 20:41:32 +00002035 // Output all of the instructions in the basic block...
2036 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2037 ++II) {
2038 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00002039 if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
Chris Lattnerf719a522004-05-09 20:41:32 +00002040 outputLValue(II);
2041 else
2042 Out << " ";
2043 visit(*II);
2044 Out << ";\n";
2045 }
2046 }
Misha Brukmanea548c02005-04-20 16:05:03 +00002047
Chris Lattnerf719a522004-05-09 20:41:32 +00002048 // Don't emit prefix or suffix for the terminator...
2049 visit(*BB->getTerminator());
2050}
2051
2052
Chris Lattner5d190e22002-05-09 20:53:56 +00002053// Specific Instruction type classes... note that all of the casts are
Misha Brukman7eb05a12003-08-18 14:43:39 +00002054// necessary because we use the instruction classes as opaque types...
Chris Lattner5d190e22002-05-09 20:53:56 +00002055//
Chris Lattnerf8b06682002-06-25 15:57:03 +00002056void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattnerde177e02006-05-23 23:39:48 +00002057 // If this is a struct return function, return the temporary struct.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00002058 bool isStructReturn = I.getParent()->getParent()->
2059 getFunctionType()->isStructReturn();
2060
2061 if (isStructReturn) {
Chris Lattnerde177e02006-05-23 23:39:48 +00002062 Out << " return StructReturn;\n";
2063 return;
2064 }
2065
Chris Lattner5d190e22002-05-09 20:53:56 +00002066 // Don't output a void return if this is the last basic block in the function
Misha Brukmanea548c02005-04-20 16:05:03 +00002067 if (I.getNumOperands() == 0 &&
Chris Lattnerf8b06682002-06-25 15:57:03 +00002068 &*--I.getParent()->getParent()->end() == I.getParent() &&
2069 !I.getParent()->size() == 1) {
Chris Lattner5d190e22002-05-09 20:53:56 +00002070 return;
Chris Lattnere7c7df02002-05-21 18:05:19 +00002071 }
Chris Lattneraf14c8d2002-05-09 03:50:42 +00002072
Chris Lattner5d190e22002-05-09 20:53:56 +00002073 Out << " return";
Chris Lattnerf8b06682002-06-25 15:57:03 +00002074 if (I.getNumOperands()) {
Misha Brukman2b1e1002005-02-14 18:52:35 +00002075 Out << ' ';
Chris Lattnerf8b06682002-06-25 15:57:03 +00002076 writeOperand(I.getOperand(0));
Chris Lattnereabc6472002-05-09 02:28:59 +00002077 }
Chris Lattner5d190e22002-05-09 20:53:56 +00002078 Out << ";\n";
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00002079}
2080
Chris Lattnerf86060f2003-04-22 20:19:52 +00002081void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattner2484a632004-05-09 03:42:48 +00002082
Chris Lattnerf86060f2003-04-22 20:19:52 +00002083 Out << " switch (";
2084 writeOperand(SI.getOperand(0));
Chris Lattner5bc7eb52003-04-23 19:15:13 +00002085 Out << ") {\n default:\n";
John Criswella564e9e2004-10-25 18:30:09 +00002086 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattner5bc7eb52003-04-23 19:15:13 +00002087 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf86060f2003-04-22 20:19:52 +00002088 Out << ";\n";
2089 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2090 Out << " case ";
2091 writeOperand(SI.getOperand(i));
2092 Out << ":\n";
2093 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswella564e9e2004-10-25 18:30:09 +00002094 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnerf86060f2003-04-22 20:19:52 +00002095 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattner484bfc42005-03-19 17:35:11 +00002096 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
Chris Lattnerf86060f2003-04-22 20:19:52 +00002097 Out << " break;\n";
2098 }
2099 Out << " }\n";
2100}
2101
Chris Lattner583dfdc2004-10-16 18:12:13 +00002102void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner53058662004-10-17 23:49:11 +00002103 Out << " /*UNREACHABLE*/;\n";
Chris Lattner583dfdc2004-10-16 18:12:13 +00002104}
2105
Chris Lattnerf719a522004-05-09 20:41:32 +00002106bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2107 /// FIXME: This should be reenabled, but loop reordering safe!!
2108 return true;
2109
Chris Lattnerbed96572005-03-18 16:12:37 +00002110 if (next(Function::iterator(From)) != Function::iterator(To))
2111 return true; // Not the direct successor, we need a goto.
Chris Lattnerf719a522004-05-09 20:41:32 +00002112
2113 //isa<SwitchInst>(From->getTerminator())
Chris Lattner27223932003-06-28 17:53:05 +00002114
Chris Lattnerf719a522004-05-09 20:41:32 +00002115 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner5d190e22002-05-09 20:53:56 +00002116 return true;
Chris Lattner5d190e22002-05-09 20:53:56 +00002117 return false;
2118}
2119
John Criswell85b38052004-10-20 14:38:39 +00002120void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmanea548c02005-04-20 16:05:03 +00002121 BasicBlock *Successor,
John Criswell85b38052004-10-20 14:38:39 +00002122 unsigned Indent) {
2123 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2124 PHINode *PN = cast<PHINode>(I);
2125 // Now we have to do the printing.
2126 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2127 if (!isa<UndefValue>(IV)) {
2128 Out << std::string(Indent, ' ');
Bill Wendling77a345f2007-02-23 22:45:08 +00002129 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
John Criswell85b38052004-10-20 14:38:39 +00002130 writeOperand(IV);
2131 Out << "; /* for PHI node */\n";
2132 }
2133 }
2134}
2135
Chris Lattner5d190e22002-05-09 20:53:56 +00002136void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner27223932003-06-28 17:53:05 +00002137 unsigned Indent) {
Chris Lattnerf719a522004-05-09 20:41:32 +00002138 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattner57ebe402003-05-03 03:14:35 +00002139 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner5d190e22002-05-09 20:53:56 +00002140 writeOperand(Succ);
2141 Out << ";\n";
2142 }
2143}
2144
Misha Brukmanacda7df2003-09-11 22:34:13 +00002145// Branch instruction printing - Avoid printing out a branch to a basic block
2146// that immediately succeeds the current one.
Chris Lattner5d190e22002-05-09 20:53:56 +00002147//
Chris Lattnerf8b06682002-06-25 15:57:03 +00002148void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattner2484a632004-05-09 03:42:48 +00002149
Chris Lattnerf8b06682002-06-25 15:57:03 +00002150 if (I.isConditional()) {
Chris Lattner1d243162003-10-12 08:12:58 +00002151 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner5d190e22002-05-09 20:53:56 +00002152 Out << " if (";
Chris Lattnerf8b06682002-06-25 15:57:03 +00002153 writeOperand(I.getCondition());
Chris Lattner5d190e22002-05-09 20:53:56 +00002154 Out << ") {\n";
Misha Brukmanea548c02005-04-20 16:05:03 +00002155
John Criswell85b38052004-10-20 14:38:39 +00002156 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerf8b06682002-06-25 15:57:03 +00002157 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmanea548c02005-04-20 16:05:03 +00002158
Chris Lattner1d243162003-10-12 08:12:58 +00002159 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner5d190e22002-05-09 20:53:56 +00002160 Out << " } else {\n";
John Criswell85b38052004-10-20 14:38:39 +00002161 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerf8b06682002-06-25 15:57:03 +00002162 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner5d190e22002-05-09 20:53:56 +00002163 }
2164 } else {
Misha Brukman7eb05a12003-08-18 14:43:39 +00002165 // First goto not necessary, assume second one is...
Chris Lattner5d190e22002-05-09 20:53:56 +00002166 Out << " if (!";
Chris Lattnerf8b06682002-06-25 15:57:03 +00002167 writeOperand(I.getCondition());
Chris Lattner5d190e22002-05-09 20:53:56 +00002168 Out << ") {\n";
2169
John Criswell85b38052004-10-20 14:38:39 +00002170 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerf8b06682002-06-25 15:57:03 +00002171 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner5d190e22002-05-09 20:53:56 +00002172 }
2173
2174 Out << " }\n";
2175 } else {
John Criswell85b38052004-10-20 14:38:39 +00002176 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerf8b06682002-06-25 15:57:03 +00002177 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner5d190e22002-05-09 20:53:56 +00002178 }
2179 Out << "\n";
2180}
2181
Chris Lattner5b5c7932003-05-03 07:11:00 +00002182// PHI nodes get copied into temporary values at the end of predecessor basic
2183// blocks. We now need to copy these temporary values into the REAL value for
2184// the PHI.
2185void CWriter::visitPHINode(PHINode &I) {
2186 writeOperand(&I);
2187 Out << "__PHI_TEMPORARY";
2188}
2189
Chris Lattner5d190e22002-05-09 20:53:56 +00002190
Chris Lattnerf8b06682002-06-25 15:57:03 +00002191void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner5d190e22002-05-09 20:53:56 +00002192 // binary instructions, shift instructions, setCond instructions.
Chris Lattner5cc12702003-04-23 19:09:22 +00002193 assert(!isa<PointerType>(I.getType()));
Brian Gaeke04bdfe62003-06-23 20:00:51 +00002194
2195 // We must cast the results of binary operations which might be promoted.
2196 bool needsCast = false;
Reid Spencere63b6512006-12-31 05:55:36 +00002197 if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty)
Brian Gaeke76109712003-06-25 03:05:33 +00002198 || (I.getType() == Type::FloatTy)) {
Brian Gaeke04bdfe62003-06-23 20:00:51 +00002199 needsCast = true;
2200 Out << "((";
Reid Spencer1fc9be32007-01-09 17:09:09 +00002201 printType(Out, I.getType(), false);
Brian Gaeke04bdfe62003-06-23 20:00:51 +00002202 Out << ")(";
2203 }
Chris Lattner5d190e22002-05-09 20:53:56 +00002204
Chris Lattner00ee68c2005-03-03 21:12:04 +00002205 // If this is a negation operation, print it out as such. For FP, we don't
2206 // want to print "-0.0 - X".
2207 if (BinaryOperator::isNeg(&I)) {
John Criswell3870f9d2005-07-14 19:41:16 +00002208 Out << "-(";
Chris Lattner00ee68c2005-03-03 21:12:04 +00002209 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswell3870f9d2005-07-14 19:41:16 +00002210 Out << ")";
Reid Spencer7eb55b32006-11-02 01:53:59 +00002211 } else if (I.getOpcode() == Instruction::FRem) {
Chris Lattner9c0a2432005-08-23 20:22:50 +00002212 // Output a call to fmod/fmodf instead of emitting a%b
2213 if (I.getType() == Type::FloatTy)
2214 Out << "fmodf(";
2215 else
2216 Out << "fmod(";
2217 writeOperand(I.getOperand(0));
2218 Out << ", ";
2219 writeOperand(I.getOperand(1));
2220 Out << ")";
Chris Lattner00ee68c2005-03-03 21:12:04 +00002221 } else {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002222
2223 // Write out the cast of the instruction's value back to the proper type
2224 // if necessary.
2225 bool NeedsClosingParens = writeInstructionCast(I);
2226
2227 // Certain instructions require the operand to be forced to a specific type
2228 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2229 // below for operand 1
2230 writeOperandWithCast(I.getOperand(0), I.getOpcode());
Chris Lattner00ee68c2005-03-03 21:12:04 +00002231
2232 switch (I.getOpcode()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002233 case Instruction::Add: Out << " + "; break;
2234 case Instruction::Sub: Out << " - "; break;
2235 case Instruction::Mul: Out << " * "; break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00002236 case Instruction::URem:
2237 case Instruction::SRem:
Reid Spencer2341c222007-02-02 02:16:23 +00002238 case Instruction::FRem: Out << " % "; break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002239 case Instruction::UDiv:
2240 case Instruction::SDiv:
Reid Spencer2341c222007-02-02 02:16:23 +00002241 case Instruction::FDiv: Out << " / "; break;
2242 case Instruction::And: Out << " & "; break;
2243 case Instruction::Or: Out << " | "; break;
2244 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner00ee68c2005-03-03 21:12:04 +00002245 case Instruction::Shl : Out << " << "; break;
Reid Spencerfdff9382006-11-08 06:47:33 +00002246 case Instruction::LShr:
2247 case Instruction::AShr: Out << " >> "; break;
Bill Wendling9bfb1e12006-12-07 22:21:48 +00002248 default: cerr << "Invalid operator type!" << I; abort();
Chris Lattner00ee68c2005-03-03 21:12:04 +00002249 }
2250
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002251 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2252 if (NeedsClosingParens)
2253 Out << "))";
Chris Lattner5d190e22002-05-09 20:53:56 +00002254 }
2255
Brian Gaeke04bdfe62003-06-23 20:00:51 +00002256 if (needsCast) {
2257 Out << "))";
2258 }
Chris Lattner5d190e22002-05-09 20:53:56 +00002259}
2260
Reid Spencer266e42b2006-12-23 06:05:41 +00002261void CWriter::visitICmpInst(ICmpInst &I) {
2262 // We must cast the results of icmp which might be promoted.
2263 bool needsCast = false;
2264
2265 // Write out the cast of the instruction's value back to the proper type
2266 // if necessary.
2267 bool NeedsClosingParens = writeInstructionCast(I);
2268
2269 // Certain icmp predicate require the operand to be forced to a specific type
2270 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2271 // below for operand 1
2272 writeOperandWithCast(I.getOperand(0), I.getPredicate());
2273
2274 switch (I.getPredicate()) {
2275 case ICmpInst::ICMP_EQ: Out << " == "; break;
2276 case ICmpInst::ICMP_NE: Out << " != "; break;
2277 case ICmpInst::ICMP_ULE:
2278 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2279 case ICmpInst::ICMP_UGE:
2280 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2281 case ICmpInst::ICMP_ULT:
2282 case ICmpInst::ICMP_SLT: Out << " < "; break;
2283 case ICmpInst::ICMP_UGT:
2284 case ICmpInst::ICMP_SGT: Out << " > "; break;
2285 default: cerr << "Invalid icmp predicate!" << I; abort();
2286 }
2287
2288 writeOperandWithCast(I.getOperand(1), I.getPredicate());
2289 if (NeedsClosingParens)
2290 Out << "))";
2291
2292 if (needsCast) {
2293 Out << "))";
2294 }
2295}
2296
2297void CWriter::visitFCmpInst(FCmpInst &I) {
Reid Spencer13cae7c2007-01-08 06:58:32 +00002298 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2299 Out << "0";
2300 return;
2301 }
2302 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2303 Out << "1";
2304 return;
2305 }
2306
2307 const char* op = 0;
2308 switch (I.getPredicate()) {
2309 default: assert(0 && "Illegal FCmp predicate");
2310 case FCmpInst::FCMP_ORD: op = "ord"; break;
2311 case FCmpInst::FCMP_UNO: op = "uno"; break;
2312 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2313 case FCmpInst::FCMP_UNE: op = "une"; break;
2314 case FCmpInst::FCMP_ULT: op = "ult"; break;
2315 case FCmpInst::FCMP_ULE: op = "ule"; break;
2316 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2317 case FCmpInst::FCMP_UGE: op = "uge"; break;
2318 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2319 case FCmpInst::FCMP_ONE: op = "one"; break;
2320 case FCmpInst::FCMP_OLT: op = "olt"; break;
2321 case FCmpInst::FCMP_OLE: op = "ole"; break;
2322 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2323 case FCmpInst::FCMP_OGE: op = "oge"; break;
2324 }
2325
2326 Out << "llvm_fcmp_" << op << "(";
Reid Spencer266e42b2006-12-23 06:05:41 +00002327 // Write the first operand
2328 writeOperand(I.getOperand(0));
Reid Spencer13cae7c2007-01-08 06:58:32 +00002329 Out << ", ";
Reid Spencer266e42b2006-12-23 06:05:41 +00002330 // Write the second operand
2331 writeOperand(I.getOperand(1));
Reid Spencer13cae7c2007-01-08 06:58:32 +00002332 Out << ")";
Reid Spencer266e42b2006-12-23 06:05:41 +00002333}
2334
Reid Spencerb9435552006-12-11 20:39:15 +00002335static const char * getFloatBitCastField(const Type *Ty) {
2336 switch (Ty->getTypeID()) {
2337 default: assert(0 && "Invalid Type");
Reid Spencere63b6512006-12-31 05:55:36 +00002338 case Type::FloatTyID: return "Float";
Reid Spencere63b6512006-12-31 05:55:36 +00002339 case Type::DoubleTyID: return "Double";
Reid Spencer7a9c62b2007-01-12 07:05:14 +00002340 case Type::IntegerTyID: {
2341 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2342 if (NumBits <= 32)
2343 return "Int32";
2344 else
2345 return "Int64";
2346 }
Reid Spencerb9435552006-12-11 20:39:15 +00002347 }
2348}
2349
Chris Lattnerf8b06682002-06-25 15:57:03 +00002350void CWriter::visitCastInst(CastInst &I) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002351 const Type *DstTy = I.getType();
2352 const Type *SrcTy = I.getOperand(0)->getType();
Misha Brukman2b1e1002005-02-14 18:52:35 +00002353 Out << '(';
Reid Spencer8bd63172006-12-17 20:24:50 +00002354 if (isFPIntBitCast(I)) {
Reid Spencerb9435552006-12-11 20:39:15 +00002355 // These int<->float and long<->double casts need to be handled specially
Bill Wendling77a345f2007-02-23 22:45:08 +00002356 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencerb9435552006-12-11 20:39:15 +00002357 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2358 writeOperand(I.getOperand(0));
Bill Wendling77a345f2007-02-23 22:45:08 +00002359 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencerb9435552006-12-11 20:39:15 +00002360 << getFloatBitCastField(I.getType());
2361 } else {
2362 printCast(I.getOpcode(), SrcTy, DstTy);
Chris Lattner4995f922007-05-03 02:57:13 +00002363 if (I.getOpcode() == Instruction::SExt && SrcTy == Type::Int1Ty) {
Reid Spencerb9435552006-12-11 20:39:15 +00002364 // Make sure we really get a sext from bool by subtracing the bool from 0
2365 Out << "0-";
2366 }
Chris Lattner4995f922007-05-03 02:57:13 +00002367 writeOperand(I.getOperand(0));
2368 if (DstTy == Type::Int1Ty &&
2369 (I.getOpcode() == Instruction::Trunc ||
2370 I.getOpcode() == Instruction::FPToUI ||
2371 I.getOpcode() == Instruction::FPToSI ||
2372 I.getOpcode() == Instruction::PtrToInt)) {
2373 // Make sure we really get a trunc to bool by anding the operand with 1
2374 Out << "&1u";
2375 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002376 }
Chris Lattner4995f922007-05-03 02:57:13 +00002377 Out << ')';
Chris Lattner5d190e22002-05-09 20:53:56 +00002378}
2379
Chris Lattner65a64e12004-03-12 05:52:14 +00002380void CWriter::visitSelectInst(SelectInst &I) {
2381 Out << "((";
2382 writeOperand(I.getCondition());
2383 Out << ") ? (";
2384 writeOperand(I.getTrueValue());
2385 Out << ") : (";
2386 writeOperand(I.getFalseValue());
Misha Brukmanea548c02005-04-20 16:05:03 +00002387 Out << "))";
Chris Lattner65a64e12004-03-12 05:52:14 +00002388}
2389
2390
Chris Lattner14d328e2004-05-09 04:30:20 +00002391void CWriter::lowerIntrinsics(Function &F) {
Reid Spencer0ef2ca82007-04-12 21:00:45 +00002392 // This is used to keep track of intrinsics that get generated to a lowered
2393 // function. We must generate the prototypes before the function body which
2394 // will only be expanded on first use (by the loop below).
2395 std::vector<Function*> prototypesToGen;
2396
2397 // Examine all the instructions in this function to find the intrinsics that
2398 // need to be lowered.
Jeff Cohenb4c610f2007-04-13 22:52:03 +00002399 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
Chris Lattner14d328e2004-05-09 04:30:20 +00002400 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2401 if (CallInst *CI = dyn_cast<CallInst>(I++))
2402 if (Function *F = CI->getCalledFunction())
2403 switch (F->getIntrinsicID()) {
2404 case Intrinsic::not_intrinsic:
2405 case Intrinsic::vastart:
2406 case Intrinsic::vacopy:
2407 case Intrinsic::vaend:
2408 case Intrinsic::returnaddress:
2409 case Intrinsic::frameaddress:
2410 case Intrinsic::setjmp:
2411 case Intrinsic::longjmp:
Chris Lattner81110732005-02-28 19:29:46 +00002412 case Intrinsic::prefetch:
Jim Laskey8f0a95f2006-03-08 19:31:15 +00002413 case Intrinsic::dbg_stoppoint:
Chris Lattnerfdb3a752006-09-09 06:17:12 +00002414 case Intrinsic::powi_f32:
2415 case Intrinsic::powi_f64:
Chris Lattner14d328e2004-05-09 04:30:20 +00002416 // We directly implement these intrinsics
2417 break;
2418 default:
Chris Lattner2b8eb372006-03-13 23:09:05 +00002419 // If this is an intrinsic that directly corresponds to a GCC
2420 // builtin, we handle it.
2421 const char *BuiltinName = "";
2422#define GET_GCC_BUILTIN_NAME
2423#include "llvm/Intrinsics.gen"
2424#undef GET_GCC_BUILTIN_NAME
2425 // If we handle it, don't lower it.
2426 if (BuiltinName[0]) break;
2427
Chris Lattner14d328e2004-05-09 04:30:20 +00002428 // All other intrinsic calls we must lower.
Chris Lattnerbed96572005-03-18 16:12:37 +00002429 Instruction *Before = 0;
Misha Brukmanea548c02005-04-20 16:05:03 +00002430 if (CI != &BB->front())
Chris Lattnerbed96572005-03-18 16:12:37 +00002431 Before = prior(BasicBlock::iterator(CI));
Misha Brukmanea548c02005-04-20 16:05:03 +00002432
Reid Spencer1e960cd2007-01-29 17:51:02 +00002433 IL->LowerIntrinsicCall(CI);
Chris Lattner14d328e2004-05-09 04:30:20 +00002434 if (Before) { // Move iterator to instruction after call
2435 I = Before; ++I;
2436 } else {
2437 I = BB->begin();
Chris Lattner0997f202004-02-14 00:31:10 +00002438 }
Reid Spencer0ef2ca82007-04-12 21:00:45 +00002439 // If the intrinsic got lowered to another call, and that call has
2440 // a definition then we need to make sure its prototype is emitted
2441 // before any calls to it.
2442 if (CallInst *Call = dyn_cast<CallInst>(I))
2443 if (Function *NewF = Call->getCalledFunction())
2444 if (!NewF->isDeclaration())
2445 prototypesToGen.push_back(NewF);
2446
Chris Lattner2b8eb372006-03-13 23:09:05 +00002447 break;
Chris Lattner14d328e2004-05-09 04:30:20 +00002448 }
Chris Lattner0997f202004-02-14 00:31:10 +00002449
Reid Spencer0ef2ca82007-04-12 21:00:45 +00002450 // We may have collected some prototypes to emit in the loop above.
2451 // Emit them now, before the function that uses them is emitted. But,
2452 // be careful not to emit them twice.
2453 std::vector<Function*>::iterator I = prototypesToGen.begin();
2454 std::vector<Function*>::iterator E = prototypesToGen.end();
2455 for ( ; I != E; ++I) {
Reid Spencer99452352007-04-12 21:57:15 +00002456 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
Reid Spencer0ef2ca82007-04-12 21:00:45 +00002457 Out << '\n';
2458 printFunctionSignature(*I, true);
2459 Out << ";\n";
Reid Spencer0ef2ca82007-04-12 21:00:45 +00002460 }
2461 }
2462}
Chris Lattner0997f202004-02-14 00:31:10 +00002463
2464
Chris Lattnerf8b06682002-06-25 15:57:03 +00002465void CWriter::visitCallInst(CallInst &I) {
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00002466 //check if we have inline asm
2467 if (isInlineAsm(I)) {
2468 visitInlineAsm(I);
2469 return;
2470 }
2471
Chris Lattner2b8eb372006-03-13 23:09:05 +00002472 bool WroteCallee = false;
2473
Chris Lattner7ba4f0a2003-05-08 18:41:45 +00002474 // Handle intrinsic function calls first...
2475 if (Function *F = I.getCalledFunction())
Brian Gaeke960707c2003-11-11 22:41:34 +00002476 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattner7ba4f0a2003-05-08 18:41:45 +00002477 switch (ID) {
Chris Lattner2b8eb372006-03-13 23:09:05 +00002478 default: {
2479 // If this is an intrinsic that directly corresponds to a GCC
2480 // builtin, we emit it here.
2481 const char *BuiltinName = "";
2482#define GET_GCC_BUILTIN_NAME
2483#include "llvm/Intrinsics.gen"
2484#undef GET_GCC_BUILTIN_NAME
2485 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2486
2487 Out << BuiltinName;
2488 WroteCallee = true;
2489 break;
2490 }
Misha Brukmanea548c02005-04-20 16:05:03 +00002491 case Intrinsic::vastart:
Chris Lattner5b337482003-10-18 05:57:43 +00002492 Out << "0; ";
Misha Brukmanea548c02005-04-20 16:05:03 +00002493
Andrew Lenharth9144ec42005-06-18 18:34:52 +00002494 Out << "va_start(*(va_list*)";
2495 writeOperand(I.getOperand(1));
2496 Out << ", ";
Chris Lattner7ba4f0a2003-05-08 18:41:45 +00002497 // Output the last argument to the enclosing function...
Chris Lattner531f9e92005-03-15 04:54:21 +00002498 if (I.getParent()->getParent()->arg_empty()) {
Bill Wendling9bfb1e12006-12-07 22:21:48 +00002499 cerr << "The C backend does not currently support zero "
2500 << "argument varargs functions, such as '"
2501 << I.getParent()->getParent()->getName() << "'!\n";
Chris Lattnerbf9584b2003-10-23 18:39:22 +00002502 abort();
2503 }
Chris Lattner31c8a9d2005-03-15 04:59:17 +00002504 writeOperand(--I.getParent()->getParent()->arg_end());
Misha Brukman2b1e1002005-02-14 18:52:35 +00002505 Out << ')';
Chris Lattner7ba4f0a2003-05-08 18:41:45 +00002506 return;
Chris Lattner071a5e52004-03-13 00:24:00 +00002507 case Intrinsic::vaend:
Chris Lattner1d787352004-08-10 00:19:16 +00002508 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
Andrew Lenharth9144ec42005-06-18 18:34:52 +00002509 Out << "0; va_end(*(va_list*)";
Chris Lattner1d787352004-08-10 00:19:16 +00002510 writeOperand(I.getOperand(1));
Misha Brukman2b1e1002005-02-14 18:52:35 +00002511 Out << ')';
Chris Lattner1d787352004-08-10 00:19:16 +00002512 } else {
2513 Out << "va_end(*(va_list*)0)";
2514 }
Chris Lattner7ba4f0a2003-05-08 18:41:45 +00002515 return;
Chris Lattner071a5e52004-03-13 00:24:00 +00002516 case Intrinsic::vacopy:
Andrew Lenharth9144ec42005-06-18 18:34:52 +00002517 Out << "0; ";
2518 Out << "va_copy(*(va_list*)";
Chris Lattner7ba4f0a2003-05-08 18:41:45 +00002519 writeOperand(I.getOperand(1));
Andrew Lenharth25314522005-06-22 21:04:42 +00002520 Out << ", *(va_list*)";
Andrew Lenharth9144ec42005-06-18 18:34:52 +00002521 writeOperand(I.getOperand(2));
Misha Brukman2b1e1002005-02-14 18:52:35 +00002522 Out << ')';
Chris Lattner7ba4f0a2003-05-08 18:41:45 +00002523 return;
Chris Lattnerf7c10882004-02-14 02:55:36 +00002524 case Intrinsic::returnaddress:
2525 Out << "__builtin_return_address(";
2526 writeOperand(I.getOperand(1));
Misha Brukman2b1e1002005-02-14 18:52:35 +00002527 Out << ')';
Chris Lattnerf7c10882004-02-14 02:55:36 +00002528 return;
2529 case Intrinsic::frameaddress:
2530 Out << "__builtin_frame_address(";
2531 writeOperand(I.getOperand(1));
Misha Brukman2b1e1002005-02-14 18:52:35 +00002532 Out << ')';
Chris Lattnerf7c10882004-02-14 02:55:36 +00002533 return;
Chris Lattnerfdb3a752006-09-09 06:17:12 +00002534 case Intrinsic::powi_f32:
2535 case Intrinsic::powi_f64:
2536 Out << "__builtin_powi(";
2537 writeOperand(I.getOperand(1));
2538 Out << ", ";
2539 writeOperand(I.getOperand(2));
2540 Out << ')';
2541 return;
Chris Lattnera95bd442004-02-15 22:51:47 +00002542 case Intrinsic::setjmp:
2543 Out << "setjmp(*(jmp_buf*)";
2544 writeOperand(I.getOperand(1));
Misha Brukman2b1e1002005-02-14 18:52:35 +00002545 Out << ')';
Chris Lattnera95bd442004-02-15 22:51:47 +00002546 return;
2547 case Intrinsic::longjmp:
2548 Out << "longjmp(*(jmp_buf*)";
2549 writeOperand(I.getOperand(1));
2550 Out << ", ";
2551 writeOperand(I.getOperand(2));
Misha Brukman2b1e1002005-02-14 18:52:35 +00002552 Out << ')';
Chris Lattnera95bd442004-02-15 22:51:47 +00002553 return;
Chris Lattner81110732005-02-28 19:29:46 +00002554 case Intrinsic::prefetch:
Chris Lattner12328e92005-02-28 19:36:15 +00002555 Out << "LLVM_PREFETCH((const void *)";
Chris Lattner81110732005-02-28 19:29:46 +00002556 writeOperand(I.getOperand(1));
2557 Out << ", ";
2558 writeOperand(I.getOperand(2));
2559 Out << ", ";
2560 writeOperand(I.getOperand(3));
2561 Out << ")";
Chris Lattner12328e92005-02-28 19:36:15 +00002562 return;
Jim Laskey8f0a95f2006-03-08 19:31:15 +00002563 case Intrinsic::dbg_stoppoint: {
2564 // If we use writeOperand directly we get a "u" suffix which is rejected
2565 // by gcc.
Jim Laskey267d39d2006-03-23 18:08:29 +00002566 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey8f0a95f2006-03-08 19:31:15 +00002567
2568 Out << "\n#line "
Jim Laskey267d39d2006-03-23 18:08:29 +00002569 << SPI.getLine()
2570 << " \"" << SPI.getDirectory()
2571 << SPI.getFileName() << "\"\n";
Jim Laskey8f0a95f2006-03-08 19:31:15 +00002572 return;
2573 }
Chris Lattner7ba4f0a2003-05-08 18:41:45 +00002574 }
2575 }
2576
Chris Lattner073f6ca2004-11-13 22:21:56 +00002577 Value *Callee = I.getCalledValue();
Misha Brukmanea548c02005-04-20 16:05:03 +00002578
Anton Korobeynikov037c8672007-01-28 13:31:35 +00002579 const PointerType *PTy = cast<PointerType>(Callee->getType());
2580 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2581
Chris Lattnerde177e02006-05-23 23:39:48 +00002582 // If this is a call to a struct-return function, assign to the first
2583 // parameter instead of passing it to the call.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00002584 bool isStructRet = FTy->isStructReturn();
Chris Lattnerde177e02006-05-23 23:39:48 +00002585 if (isStructRet) {
2586 Out << "*(";
2587 writeOperand(I.getOperand(1));
2588 Out << ") = ";
2589 }
2590
Chris Lattner561b7eb2005-05-06 06:53:07 +00002591 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattnerde177e02006-05-23 23:39:48 +00002592
2593 if (!WroteCallee) {
2594 // If this is an indirect call to a struct return function, we need to cast
2595 // the pointer.
2596 bool NeedsCast = isStructRet && !isa<Function>(Callee);
Misha Brukmanea548c02005-04-20 16:05:03 +00002597
Chris Lattnerde177e02006-05-23 23:39:48 +00002598 // GCC is a real PITA. It does not permit codegening casts of functions to
2599 // function pointers if they are in a call (it generates a trap instruction
2600 // instead!). We work around this by inserting a cast to void* in between
2601 // the function and the function pointer cast. Unfortunately, we can't just
2602 // form the constant expression here, because the folder will immediately
2603 // nuke it.
2604 //
2605 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2606 // that void* and function pointers have the same size. :( To deal with this
2607 // in the common case, we handle casts where the number of arguments passed
2608 // match exactly.
2609 //
2610 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002611 if (CE->isCast())
Chris Lattnerde177e02006-05-23 23:39:48 +00002612 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2613 NeedsCast = true;
2614 Callee = RF;
2615 }
2616
2617 if (NeedsCast) {
2618 // Ok, just cast the pointer type.
2619 Out << "((";
2620 if (!isStructRet)
2621 printType(Out, I.getCalledValue()->getType());
2622 else
2623 printStructReturnPointerFunctionType(Out,
2624 cast<PointerType>(I.getCalledValue()->getType()));
2625 Out << ")(void*)";
2626 }
2627 writeOperand(Callee);
2628 if (NeedsCast) Out << ')';
2629 }
2630
Misha Brukman2b1e1002005-02-14 18:52:35 +00002631 Out << '(';
Chris Lattner5d190e22002-05-09 20:53:56 +00002632
Chris Lattner073f6ca2004-11-13 22:21:56 +00002633 unsigned NumDeclaredParams = FTy->getNumParams();
2634
Chris Lattnerde177e02006-05-23 23:39:48 +00002635 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2636 unsigned ArgNo = 0;
2637 if (isStructRet) { // Skip struct return argument.
2638 ++AI;
2639 ++ArgNo;
2640 }
2641
Reid Spencer71b79e32007-04-09 06:17:21 +00002642 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerde177e02006-05-23 23:39:48 +00002643 bool PrintedArg = false;
Reid Spencerdf7c61d2007-01-07 03:24:48 +00002644 unsigned Idx = 1;
2645 for (; AI != AE; ++AI, ++ArgNo, ++Idx) {
Chris Lattnerde177e02006-05-23 23:39:48 +00002646 if (PrintedArg) Out << ", ";
2647 if (ArgNo < NumDeclaredParams &&
2648 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukman2b1e1002005-02-14 18:52:35 +00002649 Out << '(';
Reid Spencerdf7c61d2007-01-07 03:24:48 +00002650 printType(Out, FTy->getParamType(ArgNo),
Reid Spencera472f662007-04-11 02:44:20 +00002651 /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt));
Misha Brukman2b1e1002005-02-14 18:52:35 +00002652 Out << ')';
Chris Lattner073f6ca2004-11-13 22:21:56 +00002653 }
Chris Lattner27223932003-06-28 17:53:05 +00002654 writeOperand(*AI);
Chris Lattnerde177e02006-05-23 23:39:48 +00002655 PrintedArg = true;
Chris Lattner5d190e22002-05-09 20:53:56 +00002656 }
Misha Brukman2b1e1002005-02-14 18:52:35 +00002657 Out << ')';
Misha Brukmanea548c02005-04-20 16:05:03 +00002658}
Chris Lattner5d190e22002-05-09 20:53:56 +00002659
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00002660
2661//This converts the llvm constraint string to something gcc is expecting.
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00002662//TODO: work out platform independent constraints and factor those out
Andrew Lenharth7f739d52006-11-28 19:56:02 +00002663// of the per target tables
2664// handle multiple constraint codes
Andrew Lenharth212f15f2006-11-28 19:53:36 +00002665std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00002666
2667 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
2668
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00002669 const char** table = 0;
Andrew Lenharth212f15f2006-11-28 19:53:36 +00002670
2671 //Grab the translation table from TargetAsmInfo if it exists
2672 if (!TAsm) {
2673 std::string E;
2674 const TargetMachineRegistry::Entry* Match =
2675 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
2676 if (Match) {
2677 //Per platform Target Machines don't exist, so create it
2678 // this must be done only once
2679 const TargetMachine* TM = Match->CtorFn(*TheModule, "");
2680 TAsm = TM->getTargetAsmInfo();
2681 }
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00002682 }
Andrew Lenharth212f15f2006-11-28 19:53:36 +00002683 if (TAsm)
2684 table = TAsm->getAsmCBE();
2685
2686 //Search the translation table if it exists
2687 for (int i = 0; table && table[i]; i += 2)
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00002688 if (c.Codes[0] == table[i])
2689 return table[i+1];
2690
Andrew Lenharth8b59fd02006-11-28 22:25:32 +00002691 //default is identity
2692 return c.Codes[0];
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00002693}
2694
2695//TODO: import logic from AsmPrinter.cpp
Andrew Lenharth212f15f2006-11-28 19:53:36 +00002696static std::string gccifyAsm(std::string asmstr) {
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00002697 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
2698 if (asmstr[i] == '\n')
2699 asmstr.replace(i, 1, "\\n");
2700 else if (asmstr[i] == '\t')
2701 asmstr.replace(i, 1, "\\t");
2702 else if (asmstr[i] == '$') {
2703 if (asmstr[i + 1] == '{') {
2704 std::string::size_type a = asmstr.find_first_of(':', i + 1);
2705 std::string::size_type b = asmstr.find_first_of('}', i + 1);
2706 std::string n = "%" +
2707 asmstr.substr(a + 1, b - a - 1) +
2708 asmstr.substr(i + 2, a - i - 2);
2709 asmstr.replace(i, b - i + 1, n);
2710 i += n.size() - 1;
2711 } else
2712 asmstr.replace(i, 1, "%");
2713 }
2714 else if (asmstr[i] == '%')//grr
2715 { asmstr.replace(i, 1, "%%"); ++i;}
2716
2717 return asmstr;
2718}
2719
Andrew Lenharth7f739d52006-11-28 19:56:02 +00002720//TODO: assumptions about what consume arguments from the call are likely wrong
2721// handle communitivity
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00002722void CWriter::visitInlineAsm(CallInst &CI) {
2723 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00002724 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
2725 std::vector<std::pair<std::string, Value*> > Input;
2726 std::vector<std::pair<std::string, Value*> > Output;
2727 std::string Clobber;
2728 int count = CI.getType() == Type::VoidTy ? 1 : 0;
2729 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
2730 E = Constraints.end(); I != E; ++I) {
2731 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
2732 std::string c =
Andrew Lenharth212f15f2006-11-28 19:53:36 +00002733 InterpretASMConstraint(*I);
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00002734 switch(I->Type) {
2735 default:
2736 assert(0 && "Unknown asm constraint");
2737 break;
2738 case InlineAsm::isInput: {
2739 if (c.size()) {
2740 Input.push_back(std::make_pair(c, count ? CI.getOperand(count) : &CI));
2741 ++count; //consume arg
2742 }
2743 break;
2744 }
2745 case InlineAsm::isOutput: {
2746 if (c.size()) {
2747 Output.push_back(std::make_pair("="+((I->isEarlyClobber ? "&" : "")+c),
2748 count ? CI.getOperand(count) : &CI));
2749 ++count; //consume arg
2750 }
2751 break;
2752 }
2753 case InlineAsm::isClobber: {
2754 if (c.size())
2755 Clobber += ",\"" + c + "\"";
2756 break;
2757 }
2758 }
2759 }
2760
2761 //fix up the asm string for gcc
Andrew Lenharth212f15f2006-11-28 19:53:36 +00002762 std::string asmstr = gccifyAsm(as->getAsmString());
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00002763
2764 Out << "__asm__ volatile (\"" << asmstr << "\"\n";
2765 Out << " :";
2766 for (std::vector<std::pair<std::string, Value*> >::iterator I = Output.begin(),
2767 E = Output.end(); I != E; ++I) {
2768 Out << "\"" << I->first << "\"(";
2769 writeOperandRaw(I->second);
2770 Out << ")";
2771 if (I + 1 != E)
2772 Out << ",";
2773 }
2774 Out << "\n :";
2775 for (std::vector<std::pair<std::string, Value*> >::iterator I = Input.begin(),
2776 E = Input.end(); I != E; ++I) {
2777 Out << "\"" << I->first << "\"(";
2778 writeOperandRaw(I->second);
2779 Out << ")";
2780 if (I + 1 != E)
2781 Out << ",";
2782 }
Andrew Lenharth904ca9c2006-11-28 23:07:32 +00002783 if (Clobber.size())
2784 Out << "\n :" << Clobber.substr(1);
2785 Out << ")";
Andrew Lenharthe8c64ab2006-11-27 23:50:49 +00002786}
2787
Chris Lattnerf8b06682002-06-25 15:57:03 +00002788void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattner0591bb52004-02-13 23:18:48 +00002789 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner5d190e22002-05-09 20:53:56 +00002790}
2791
Chris Lattnerf8b06682002-06-25 15:57:03 +00002792void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukman2b1e1002005-02-14 18:52:35 +00002793 Out << '(';
Nick Hildenbrandtcdf2a182002-11-18 20:55:50 +00002794 printType(Out, I.getType());
Chris Lattner5d190e22002-05-09 20:53:56 +00002795 Out << ") alloca(sizeof(";
Nick Hildenbrandtcdf2a182002-11-18 20:55:50 +00002796 printType(Out, I.getType()->getElementType());
Misha Brukman2b1e1002005-02-14 18:52:35 +00002797 Out << ')';
Chris Lattnerf8b06682002-06-25 15:57:03 +00002798 if (I.isArrayAllocation()) {
Chris Lattner5d190e22002-05-09 20:53:56 +00002799 Out << " * " ;
Chris Lattnerf8b06682002-06-25 15:57:03 +00002800 writeOperand(I.getOperand(0));
Chris Lattner5d190e22002-05-09 20:53:56 +00002801 }
Misha Brukman2b1e1002005-02-14 18:52:35 +00002802 Out << ')';
Chris Lattner5d190e22002-05-09 20:53:56 +00002803}
2804
Chris Lattnerf8b06682002-06-25 15:57:03 +00002805void CWriter::visitFreeInst(FreeInst &I) {
Chris Lattner0591bb52004-02-13 23:18:48 +00002806 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner5d190e22002-05-09 20:53:56 +00002807}
2808
Chris Lattner637ee392003-11-25 20:49:55 +00002809void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
2810 gep_type_iterator E) {
Chris Lattnerf3a86f02002-08-19 23:09:46 +00002811 bool HasImplicitAddress = false;
2812 // If accessing a global value with no indexing, avoid *(&GV) syndrome
Reid Spencerde46e482006-11-02 20:25:50 +00002813 if (isa<GlobalValue>(Ptr)) {
Chris Lattnerf3a86f02002-08-19 23:09:46 +00002814 HasImplicitAddress = true;
Chris Lattnerfb70cf52003-06-17 04:39:14 +00002815 } else if (isDirectAlloca(Ptr)) {
2816 HasImplicitAddress = true;
Chris Lattnerd4c569c2002-05-09 21:18:38 +00002817 }
Chris Lattner5d190e22002-05-09 20:53:56 +00002818
Chris Lattnerf3a86f02002-08-19 23:09:46 +00002819 if (I == E) {
2820 if (!HasImplicitAddress)
Misha Brukman2b1e1002005-02-14 18:52:35 +00002821 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner5d190e22002-05-09 20:53:56 +00002822
Chris Lattnerf3a86f02002-08-19 23:09:46 +00002823 writeOperandInternal(Ptr);
2824 return;
2825 }
2826
Chris Lattner637ee392003-11-25 20:49:55 +00002827 const Constant *CI = dyn_cast<Constant>(I.getOperand());
Chris Lattnerf3a86f02002-08-19 23:09:46 +00002828 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
2829 Out << "(&";
2830
2831 writeOperandInternal(Ptr);
2832
Nick Hildenbrandt88e87782002-09-25 20:29:26 +00002833 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Misha Brukman2b1e1002005-02-14 18:52:35 +00002834 Out << ')';
Nick Hildenbrandt88e87782002-09-25 20:29:26 +00002835 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
2836 }
Chris Lattner5d190e22002-05-09 20:53:56 +00002837
Nick Hildenbrandt88e87782002-09-25 20:29:26 +00002838 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
2839 "Can only have implicit address with direct accessing");
2840
2841 if (HasImplicitAddress) {
2842 ++I;
Chris Lattner637ee392003-11-25 20:49:55 +00002843 } else if (CI && CI->isNullValue()) {
2844 gep_type_iterator TmpI = I; ++TmpI;
2845
Nick Hildenbrandt88e87782002-09-25 20:29:26 +00002846 // Print out the -> operator if possible...
Chris Lattner637ee392003-11-25 20:49:55 +00002847 if (TmpI != E && isa<StructType>(*TmpI)) {
Chris Lattnerf3a86f02002-08-19 23:09:46 +00002848 Out << (HasImplicitAddress ? "." : "->");
Reid Spencere0fc4df2006-10-20 07:07:24 +00002849 Out << "field" << cast<ConstantInt>(TmpI.getOperand())->getZExtValue();
Chris Lattner637ee392003-11-25 20:49:55 +00002850 I = ++TmpI;
2851 }
Chris Lattner5d190e22002-05-09 20:53:56 +00002852 }
Chris Lattner030effa2002-08-22 22:48:55 +00002853
Chris Lattner5d190e22002-05-09 20:53:56 +00002854 for (; I != E; ++I)
Chris Lattner637ee392003-11-25 20:49:55 +00002855 if (isa<StructType>(*I)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002856 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
Chris Lattner5d190e22002-05-09 20:53:56 +00002857 } else {
Misha Brukman2b1e1002005-02-14 18:52:35 +00002858 Out << '[';
Chris Lattner637ee392003-11-25 20:49:55 +00002859 writeOperand(I.getOperand());
Misha Brukman2b1e1002005-02-14 18:52:35 +00002860 Out << ']';
Chris Lattner5d190e22002-05-09 20:53:56 +00002861 }
2862}
2863
Chris Lattnerf8b06682002-06-25 15:57:03 +00002864void CWriter::visitLoadInst(LoadInst &I) {
Misha Brukman2b1e1002005-02-14 18:52:35 +00002865 Out << '*';
Chris Lattner7afbdca2005-02-14 16:47:52 +00002866 if (I.isVolatile()) {
Chris Lattner3bef66f2005-02-15 05:52:14 +00002867 Out << "((";
Reid Spencer1fc9be32007-01-09 17:09:09 +00002868 printType(Out, I.getType(), false, "volatile*");
Chris Lattner5635cc02005-09-27 20:52:44 +00002869 Out << ")";
Chris Lattner7afbdca2005-02-14 16:47:52 +00002870 }
2871
Chris Lattner030effa2002-08-22 22:48:55 +00002872 writeOperand(I.getOperand(0));
Chris Lattner7afbdca2005-02-14 16:47:52 +00002873
2874 if (I.isVolatile())
Misha Brukman20238eb2005-03-08 00:26:08 +00002875 Out << ')';
Chris Lattner5d190e22002-05-09 20:53:56 +00002876}
2877
Chris Lattnerf8b06682002-06-25 15:57:03 +00002878void CWriter::visitStoreInst(StoreInst &I) {
Misha Brukman2b1e1002005-02-14 18:52:35 +00002879 Out << '*';
Chris Lattner7afbdca2005-02-14 16:47:52 +00002880 if (I.isVolatile()) {
Chris Lattner3bef66f2005-02-15 05:52:14 +00002881 Out << "((";
Reid Spencer1fc9be32007-01-09 17:09:09 +00002882 printType(Out, I.getOperand(0)->getType(), false, " volatile*");
Chris Lattner5635cc02005-09-27 20:52:44 +00002883 Out << ")";
Chris Lattner7afbdca2005-02-14 16:47:52 +00002884 }
Chris Lattner030effa2002-08-22 22:48:55 +00002885 writeOperand(I.getPointerOperand());
Misha Brukman20238eb2005-03-08 00:26:08 +00002886 if (I.isVolatile()) Out << ')';
Chris Lattner5d190e22002-05-09 20:53:56 +00002887 Out << " = ";
Reid Spencer1f876602007-03-03 16:33:33 +00002888 Value *Operand = I.getOperand(0);
2889 Constant *BitMask = 0;
2890 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
2891 if (!ITy->isPowerOf2ByteWidth())
2892 // We have a bit width that doesn't match an even power-of-2 byte
2893 // size. Consequently we must & the value with the type's bit mask
2894 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
2895 if (BitMask)
2896 Out << "((";
2897 writeOperand(Operand);
2898 if (BitMask) {
2899 Out << ") & ";
2900 printConstant(BitMask);
2901 Out << ")";
2902 }
Chris Lattner5d190e22002-05-09 20:53:56 +00002903}
2904
Chris Lattnerf8b06682002-06-25 15:57:03 +00002905void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Misha Brukman2b1e1002005-02-14 18:52:35 +00002906 Out << '&';
Chris Lattner637ee392003-11-25 20:49:55 +00002907 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2908 gep_type_end(I));
Chris Lattner5d190e22002-05-09 20:53:56 +00002909}
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00002910
Chris Lattner5b337482003-10-18 05:57:43 +00002911void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth9144ec42005-06-18 18:34:52 +00002912 Out << "va_arg(*(va_list*)";
Chris Lattner5b337482003-10-18 05:57:43 +00002913 writeOperand(I.getOperand(0));
Andrew Lenharth9144ec42005-06-18 18:34:52 +00002914 Out << ", ";
Chris Lattner7af7d942003-11-03 01:01:59 +00002915 printType(Out, I.getType());
Andrew Lenharth9144ec42005-06-18 18:34:52 +00002916 Out << ");\n ";
Chris Lattner5b337482003-10-18 05:57:43 +00002917}
2918
Sumant Kowshikcf3afd92002-05-08 18:09:58 +00002919//===----------------------------------------------------------------------===//
2920// External Interface declaration
2921//===----------------------------------------------------------------------===//
2922
Chris Lattner12e97302006-09-04 04:14:57 +00002923bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2924 std::ostream &o,
2925 CodeGenFileType FileType,
2926 bool Fast) {
Chris Lattnerf11f48b2005-06-25 02:48:37 +00002927 if (FileType != TargetMachine::AssemblyFile) return true;
2928
Chris Lattner6e4edd62004-05-23 21:23:35 +00002929 PM.add(createLowerGCPass());
Chris Lattner1a678c62005-03-03 01:04:50 +00002930 PM.add(createLowerAllocationsPass(true));
Chris Lattnerd2b6e182004-02-13 23:00:29 +00002931 PM.add(createLowerInvokePass());
Chris Lattner9b9a8392005-11-02 17:42:58 +00002932 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerd2d174d2006-02-13 22:22:42 +00002933 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattner6f95ab72006-03-23 05:43:16 +00002934 PM.add(new CWriter(o));
Chris Lattner0591bb52004-02-13 23:18:48 +00002935 return false;
2936}