blob: caf91c882eeff7e4a4680e3fc80d0782b47bd84c [file] [log] [blame]
Reid Spencer76796932007-01-10 04:17:32 +00001//===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
Misha Brukmand6a29a52005-04-20 16:05:03 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmand6a29a52005-04-20 16:05:03 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00009//
Chris Lattner897bf0d2004-02-13 06:18:21 +000010// This library converts LLVM code to C code, compilable by GCC and other C
11// compilers.
Chris Lattner16c7bb22002-05-09 02:28:59 +000012//
Chris Lattneredd8ce12003-05-03 03:14:35 +000013//===----------------------------------------------------------------------===//
Chris Lattner84e66652003-05-03 07:11:00 +000014
Chris Lattnerf31182a2004-02-13 23:18:48 +000015#include "CTargetMachine.h"
Chris Lattner0c54d892006-05-23 23:39:48 +000016#include "llvm/CallingConv.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000017#include "llvm/Constants.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000018#include "llvm/DerivedTypes.h"
19#include "llvm/Module.h"
Chris Lattnera9f5e052003-04-22 20:19:52 +000020#include "llvm/Instructions.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000021#include "llvm/Pass.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000022#include "llvm/PassManager.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000023#include "llvm/TypeSymbolTable.h"
Chris Lattner18ac3c82003-05-08 18:41:45 +000024#include "llvm/Intrinsics.h"
Jim Laskey580418e2006-03-23 18:08:29 +000025#include "llvm/IntrinsicInst.h"
Andrew Lenharth29c277f2006-11-27 23:50:49 +000026#include "llvm/InlineAsm.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000027#include "llvm/Analysis/ConstantsScanner.h"
Chris Lattnercb3ad012004-05-09 20:41:32 +000028#include "llvm/Analysis/FindUsedTypes.h"
29#include "llvm/Analysis/LoopInfo.h"
Gordon Henriksence224772008-01-07 01:30:38 +000030#include "llvm/CodeGen/Passes.h"
Chris Lattner30483732004-06-20 07:49:54 +000031#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000032#include "llvm/Transforms/Scalar.h"
Chris Lattnerd36c9702004-07-11 02:48:49 +000033#include "llvm/Target/TargetMachineRegistry.h"
Andrew Lenharthe0cf0752006-11-28 19:53:36 +000034#include "llvm/Target/TargetAsmInfo.h"
Reid Spencer519e2392007-01-29 17:51:02 +000035#include "llvm/Target/TargetData.h"
Chris Lattner23e90702003-11-25 20:49:55 +000036#include "llvm/Support/CallSite.h"
Chris Lattnera05e0ec2004-05-09 03:42:48 +000037#include "llvm/Support/CFG.h"
Torok Edwindac237e2009-07-08 20:53:28 +000038#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000039#include "llvm/Support/FormattedStream.h"
Chris Lattner23e90702003-11-25 20:49:55 +000040#include "llvm/Support/GetElementPtrTypeIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000041#include "llvm/Support/InstVisitor.h"
Brian Gaeke49a178b2003-07-25 20:21:06 +000042#include "llvm/Support/Mangler.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000043#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000044#include "llvm/ADT/StringExtras.h"
Chris Lattner67c2d182005-03-18 16:12:37 +000045#include "llvm/ADT/STLExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000046#include "llvm/Support/MathExtras.h"
47#include "llvm/Config/config.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000048#include <algorithm>
Bill Wendling1a097e32006-12-07 23:41:45 +000049#include <sstream>
Chris Lattner897bf0d2004-02-13 06:18:21 +000050using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000051
Oscar Fuentes92adc192008-11-15 21:36:30 +000052/// CBackendTargetMachineModule - Note that this is used on hosts that
53/// cannot link in a library unless there are references into the
54/// library. In particular, it seems that it is not possible to get
55/// things to work on Win32 without this. Though it is unused, do not
56/// remove it.
57extern "C" int CBackendTargetMachineModule;
58int CBackendTargetMachineModule = 0;
59
Dan Gohman844731a2008-05-13 00:00:25 +000060// Register the target.
Dan Gohmanb8cab922008-10-14 20:25:08 +000061static RegisterTarget<CTargetMachine> X("c", "C backend");
Chris Lattnerd36c9702004-07-11 02:48:49 +000062
Bob Wilsona96751f2009-06-23 23:59:40 +000063// Force static initialization.
64extern "C" void LLVMInitializeCBackendTarget() { }
Douglas Gregor1555a232009-06-16 20:12:29 +000065
Dan Gohman844731a2008-05-13 00:00:25 +000066namespace {
Chris Lattnerf9a05322006-02-13 22:22:42 +000067 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
68 /// any unnamed structure types that are used by the program, and merges
69 /// external functions with the same name.
Chris Lattner68758072004-05-09 06:20:51 +000070 ///
Chris Lattnerf9a05322006-02-13 22:22:42 +000071 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
Devang Patel794fd752007-05-01 21:15:47 +000072 public:
Devang Patel19974732007-05-03 01:11:54 +000073 static char ID;
Devang Patel794fd752007-05-01 21:15:47 +000074 CBackendNameAllUsedStructsAndMergeFunctions()
Dan Gohmanae73dc12008-09-04 17:05:41 +000075 : ModulePass(&ID) {}
Chris Lattner68758072004-05-09 06:20:51 +000076 void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.addRequired<FindUsedTypes>();
78 }
79
80 virtual const char *getPassName() const {
81 return "C backend type canonicalizer";
82 }
83
Chris Lattnerb12914b2004-09-20 04:48:05 +000084 virtual bool runOnModule(Module &M);
Chris Lattner68758072004-05-09 06:20:51 +000085 };
Misha Brukmand6a29a52005-04-20 16:05:03 +000086
Devang Patel19974732007-05-03 01:11:54 +000087 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
Devang Patel794fd752007-05-01 21:15:47 +000088
Chris Lattner68758072004-05-09 06:20:51 +000089 /// CWriter - This class is the main chunk of code that converts an LLVM
90 /// module to a C translation unit.
91 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
David Greene71847812009-07-14 20:18:05 +000092 formatted_raw_ostream &Out;
Reid Spencer519e2392007-01-29 17:51:02 +000093 IntrinsicLowering *IL;
Brian Gaeked9fb37a2003-07-24 20:20:44 +000094 Mangler *Mang;
Chris Lattnercb3ad012004-05-09 20:41:32 +000095 LoopInfo *LI;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000096 const Module *TheModule;
Andrew Lenharthe0cf0752006-11-28 19:53:36 +000097 const TargetAsmInfo* TAsm;
Reid Spencer519e2392007-01-29 17:51:02 +000098 const TargetData* TD;
Chris Lattneredd8ce12003-05-03 03:14:35 +000099 std::map<const Type *, std::string> TypeNames;
Chris Lattneredd8ce12003-05-03 03:14:35 +0000100 std::map<const ConstantFP *, unsigned> FPConstantMap;
Reid Spencer69f80a62007-04-12 21:00:45 +0000101 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
Chris Lattnere05252b42008-03-02 08:07:24 +0000102 std::set<const Argument*> ByValParams;
Chris Lattneraecc22a2008-10-22 04:53:16 +0000103 unsigned FPCounter;
Owen Anderson52132bf2009-06-26 19:48:37 +0000104 unsigned OpaqueCounter;
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000105 DenseMap<const Value*, unsigned> AnonValueNumbers;
106 unsigned NextAnonValueNumber;
Reid Spencer69f80a62007-04-12 21:00:45 +0000107
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000108 public:
Devang Patel19974732007-05-03 01:11:54 +0000109 static char ID;
David Greene71847812009-07-14 20:18:05 +0000110 explicit CWriter(formatted_raw_ostream &o)
Dan Gohmanae73dc12008-09-04 17:05:41 +0000111 : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0),
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000112 TheModule(0), TAsm(0), TD(0), OpaqueCounter(0), NextAnonValueNumber(0) {
Chris Lattneraecc22a2008-10-22 04:53:16 +0000113 FPCounter = 0;
114 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000115
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000116 virtual const char *getPassName() const { return "C backend"; }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000117
Chris Lattnercb3ad012004-05-09 20:41:32 +0000118 void getAnalysisUsage(AnalysisUsage &AU) const {
119 AU.addRequired<LoopInfo>();
120 AU.setPreservesAll();
121 }
122
Chris Lattner68758072004-05-09 06:20:51 +0000123 virtual bool doInitialization(Module &M);
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000124
Chris Lattner68758072004-05-09 06:20:51 +0000125 bool runOnFunction(Function &F) {
Chris Lattner9062d9a2009-04-17 00:26:12 +0000126 // Do not codegen any 'available_externally' functions at all, they have
127 // definitions outside the translation unit.
128 if (F.hasAvailableExternallyLinkage())
129 return false;
130
Chris Lattnercb3ad012004-05-09 20:41:32 +0000131 LI = &getAnalysis<LoopInfo>();
132
Chris Lattner3150e2d2004-12-05 06:49:44 +0000133 // Get rid of intrinsics we can't handle.
134 lowerIntrinsics(F);
135
Chris Lattner68758072004-05-09 06:20:51 +0000136 // Output all floating point constants that cannot be printed accurately.
137 printFloatingPointConstants(F);
Chris Lattner3150e2d2004-12-05 06:49:44 +0000138
Chris Lattner68758072004-05-09 06:20:51 +0000139 printFunction(F);
Chris Lattner68758072004-05-09 06:20:51 +0000140 return false;
141 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000142
Chris Lattner68758072004-05-09 06:20:51 +0000143 virtual bool doFinalization(Module &M) {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000144 // Free memory...
Nuno Lopesbb6382e2009-01-13 23:35:49 +0000145 delete IL;
146 delete TD;
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000147 delete Mang;
Evan Cheng588c6f82008-01-11 09:12:49 +0000148 FPConstantMap.clear();
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000149 TypeNames.clear();
Evan Cheng588c6f82008-01-11 09:12:49 +0000150 ByValParams.clear();
Chris Lattnere05252b42008-03-02 08:07:24 +0000151 intrinsicPrototypesAlreadyGenerated.clear();
Chris Lattnercb3ad012004-05-09 20:41:32 +0000152 return false;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000153 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000154
David Greene71847812009-07-14 20:18:05 +0000155 raw_ostream &printType(formatted_raw_ostream &Out,
156 const Type *Ty,
157 bool isSigned = false,
158 const std::string &VariableName = "",
159 bool IgnoreName = false,
160 const AttrListPtr &PAL = AttrListPtr());
Owen Andersoncb371882008-08-21 00:14:44 +0000161 std::ostream &printType(std::ostream &Out, const Type *Ty,
162 bool isSigned = false,
163 const std::string &VariableName = "",
164 bool IgnoreName = false,
Devang Patel05988662008-09-25 21:00:45 +0000165 const AttrListPtr &PAL = AttrListPtr());
David Greene71847812009-07-14 20:18:05 +0000166 raw_ostream &printSimpleType(formatted_raw_ostream &Out,
167 const Type *Ty,
168 bool isSigned,
169 const std::string &NameSoFar = "");
Owen Andersoncb371882008-08-21 00:14:44 +0000170 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
171 bool isSigned,
172 const std::string &NameSoFar = "");
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000173
David Greene71847812009-07-14 20:18:05 +0000174 void printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
Devang Patel05988662008-09-25 21:00:45 +0000175 const AttrListPtr &PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +0000176 const PointerType *Ty);
Chris Lattnere05252b42008-03-02 08:07:24 +0000177
178 /// writeOperandDeref - Print the result of dereferencing the specified
179 /// operand with '*'. This is equivalent to printing '*' then using
180 /// writeOperand, but avoids excess syntax in some cases.
181 void writeOperandDeref(Value *Operand) {
182 if (isAddressExposed(Operand)) {
183 // Already something with an address exposed.
184 writeOperandInternal(Operand);
185 } else {
186 Out << "*(";
187 writeOperand(Operand);
188 Out << ")";
189 }
190 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000191
Dan Gohman9f8d5712008-07-24 17:57:48 +0000192 void writeOperand(Value *Operand, bool Static = false);
Chris Lattnere56d9462008-05-31 09:23:55 +0000193 void writeInstComputationInline(Instruction &I);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000194 void writeOperandInternal(Value *Operand, bool Static = false);
Reid Spencer1628cec2006-10-26 06:15:43 +0000195 void writeOperandWithCast(Value* Operand, unsigned Opcode);
Chris Lattner5bda9e42007-09-15 06:51:03 +0000196 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000197 bool writeInstructionCast(const Instruction &I);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000198
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +0000199 void writeMemoryAccess(Value *Operand, const Type *OperandType,
200 bool IsVolatile, unsigned Alignment);
201
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000202 private :
Andrew Lenharthe0cf0752006-11-28 19:53:36 +0000203 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
204
Chris Lattnerc2421432004-05-09 04:30:20 +0000205 void lowerIntrinsics(Function &F);
Chris Lattner4ef51372004-02-14 00:31:10 +0000206
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000207 void printModule(Module *M);
Reid Spencer78d033e2007-01-06 07:24:44 +0000208 void printModuleTypes(const TypeSymbolTable &ST);
Dan Gohman193c2352008-06-02 21:30:49 +0000209 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
Chris Lattner68758072004-05-09 06:20:51 +0000210 void printFloatingPointConstants(Function &F);
Chris Lattneraecc22a2008-10-22 04:53:16 +0000211 void printFloatingPointConstants(const Constant *C);
Chris Lattner4cda8352002-08-20 16:55:48 +0000212 void printFunctionSignature(const Function *F, bool Prototype);
213
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000214 void printFunction(Function &);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000215 void printBasicBlock(BasicBlock *BB);
216 void printLoop(Loop *L);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000217
Reid Spencer3da59db2006-11-27 01:05:10 +0000218 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000219 void printConstant(Constant *CPV, bool Static);
Reid Spencer1628cec2006-10-26 06:15:43 +0000220 void printConstantWithCast(Constant *CPV, unsigned Opcode);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000221 bool printConstExprCast(const ConstantExpr *CE, bool Static);
222 void printConstantArray(ConstantArray *CPA, bool Static);
223 void printConstantVector(ConstantVector *CV, bool Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000224
Chris Lattnere05252b42008-03-02 08:07:24 +0000225 /// isAddressExposed - Return true if the specified value's name needs to
226 /// have its address taken in order to get a C value of the correct type.
227 /// This happens for global variables, byval parameters, and direct allocas.
228 bool isAddressExposed(const Value *V) const {
229 if (const Argument *A = dyn_cast<Argument>(V))
230 return ByValParams.count(A);
231 return isa<GlobalVariable>(V) || isDirectAlloca(V);
232 }
233
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000234 // isInlinableInst - Attempt to inline instructions into their uses to build
235 // trees as much as possible. To do this, we have to consistently decide
236 // what is acceptable to inline, so that variable declarations don't get
237 // printed and an extra copy of the expr is not emitted.
238 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000239 static bool isInlinableInst(const Instruction &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000240 // Always inline cmp instructions, even if they are shared by multiple
Chris Lattner433e25a2004-05-20 20:25:50 +0000241 // expressions. GCC generates horrible code if we don't.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000242 if (isa<CmpInst>(I))
243 return true;
Chris Lattner433e25a2004-05-20 20:25:50 +0000244
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000245 // Must be an expression, must be used exactly once. If it is dead, we
246 // emit it inline where it would go.
Chris Lattnerfd059242003-10-15 16:48:29 +0000247 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
Misha Brukmand6a29a52005-04-20 16:05:03 +0000248 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Dan Gohman193c2352008-06-02 21:30:49 +0000249 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
250 isa<InsertValueInst>(I))
Chris Lattnerd4e8d312003-07-23 20:45:31 +0000251 // Don't inline a load across a store or other bad things!
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000252 return false;
253
Chris Lattnerb1855ad2008-03-02 05:41:07 +0000254 // Must not be used in inline asm, extractelement, or shufflevector.
255 if (I.hasOneUse()) {
256 const Instruction &User = cast<Instruction>(*I.use_back());
257 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
258 isa<ShuffleVectorInst>(User))
259 return false;
260 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000261
Reid Spencer555a0b12006-12-11 20:39:15 +0000262 // Only inline instruction it if it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000263 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000264 }
265
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000266 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
267 // variables which are accessed with the & operator. This causes GCC to
268 // generate significantly better code than to emit alloca calls directly.
269 //
270 static const AllocaInst *isDirectAlloca(const Value *V) {
271 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
272 if (!AI) return false;
273 if (AI->isArrayAllocation())
274 return 0; // FIXME: we can also inline fixed size array allocas!
Chris Lattner02a3be02003-09-20 14:39:18 +0000275 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000276 return 0;
277 return AI;
278 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000279
280 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
281 static bool isInlineAsm(const Instruction& I) {
282 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
283 return true;
284 return false;
285 }
286
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000287 // Instruction visitation functions
288 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000289
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000290 void visitReturnInst(ReturnInst &I);
291 void visitBranchInst(BranchInst &I);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000292 void visitSwitchInst(SwitchInst &I);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000293 void visitInvokeInst(InvokeInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000294 llvm_unreachable("Lowerinvoke pass didn't work!");
Chris Lattnercb3ad012004-05-09 20:41:32 +0000295 }
296
297 void visitUnwindInst(UnwindInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000298 llvm_unreachable("Lowerinvoke pass didn't work!");
Chris Lattnercb3ad012004-05-09 20:41:32 +0000299 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000300 void visitUnreachableInst(UnreachableInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000301
Chris Lattner84e66652003-05-03 07:11:00 +0000302 void visitPHINode(PHINode &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000303 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000304 void visitICmpInst(ICmpInst &I);
305 void visitFCmpInst(FCmpInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000306
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000307 void visitCastInst (CastInst &I);
Chris Lattner9f24a072004-03-12 05:52:14 +0000308 void visitSelectInst(SelectInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000309 void visitCallInst (CallInst &I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000310 void visitInlineAsm(CallInst &I);
Chris Lattner2299fec2008-03-02 08:29:41 +0000311 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000312
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000313 void visitMallocInst(MallocInst &I);
314 void visitAllocaInst(AllocaInst &I);
315 void visitFreeInst (FreeInst &I);
316 void visitLoadInst (LoadInst &I);
317 void visitStoreInst (StoreInst &I);
318 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner4d45bd02003-10-18 05:57:43 +0000319 void visitVAArgInst (VAArgInst &I);
Chris Lattner33a44d92008-03-02 03:52:39 +0000320
321 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner0452ed62008-03-02 03:57:08 +0000322 void visitExtractElementInst(ExtractElementInst &I);
Chris Lattnerb1855ad2008-03-02 05:41:07 +0000323 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000324
Dan Gohman193c2352008-06-02 21:30:49 +0000325 void visitInsertValueInst(InsertValueInst &I);
326 void visitExtractValueInst(ExtractValueInst &I);
327
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000328 void visitInstruction(Instruction &I) {
Torok Edwindac237e2009-07-08 20:53:28 +0000329#ifndef NDEBUG
Bill Wendlingf5da1332006-12-07 22:21:48 +0000330 cerr << "C Writer does not know about " << I;
Torok Edwindac237e2009-07-08 20:53:28 +0000331#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000332 llvm_unreachable(0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000333 }
334
335 void outputLValue(Instruction *I) {
Bill Wendling145aad02007-02-23 22:45:08 +0000336 Out << " " << GetValueName(I) << " = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000337 }
Chris Lattnercb3ad012004-05-09 20:41:32 +0000338
339 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
John Criswell57bbfce2004-10-20 14:38:39 +0000340 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
341 BasicBlock *Successor, unsigned Indent);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000342 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
343 unsigned Indent);
Chris Lattnere05252b42008-03-02 08:07:24 +0000344 void printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohman9f8d5712008-07-24 17:57:48 +0000345 gep_type_iterator E, bool Static);
Bill Wendling145aad02007-02-23 22:45:08 +0000346
347 std::string GetValueName(const Value *Operand);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000348 };
Chris Lattner4ef51372004-02-14 00:31:10 +0000349}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000350
Devang Patel19974732007-05-03 01:11:54 +0000351char CWriter::ID = 0;
Devang Patel794fd752007-05-01 21:15:47 +0000352
Chris Lattner68758072004-05-09 06:20:51 +0000353/// This method inserts names for any unnamed structure types that are used by
354/// the program, and removes names from structure types that are not used by the
355/// program.
356///
Chris Lattnerf9a05322006-02-13 22:22:42 +0000357bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
Chris Lattner68758072004-05-09 06:20:51 +0000358 // Get a set of types that are used by the program...
359 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000360
Chris Lattner68758072004-05-09 06:20:51 +0000361 // Loop over the module symbol table, removing types from UT that are
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000362 // already named, and removing names for types that are not used.
Chris Lattner68758072004-05-09 06:20:51 +0000363 //
Reid Spencer78d033e2007-01-06 07:24:44 +0000364 TypeSymbolTable &TST = M.getTypeSymbolTable();
365 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
Reid Spencer9231ac82004-05-25 08:53:40 +0000366 TI != TE; ) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000367 TypeSymbolTable::iterator I = TI++;
Chris Lattner19e8b0c2007-01-16 07:22:23 +0000368
Dan Gohman193c2352008-06-02 21:30:49 +0000369 // If this isn't a struct or array type, remove it from our set of types
370 // to name. This simplifies emission later.
371 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
372 !isa<ArrayType>(I->second)) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000373 TST.remove(I);
Chris Lattner19e8b0c2007-01-16 07:22:23 +0000374 } else {
375 // If this is not used, remove it from the symbol table.
376 std::set<const Type *>::iterator UTI = UT.find(I->second);
377 if (UTI == UT.end())
378 TST.remove(I);
379 else
380 UT.erase(UTI); // Only keep one name for this type.
381 }
Reid Spencer9231ac82004-05-25 08:53:40 +0000382 }
Chris Lattner68758072004-05-09 06:20:51 +0000383
384 // UT now contains types that are not named. Loop over it, naming
385 // structure types.
386 //
387 bool Changed = false;
Chris Lattner9d1af972004-05-28 05:47:27 +0000388 unsigned RenameCounter = 0;
Chris Lattner68758072004-05-09 06:20:51 +0000389 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
390 I != E; ++I)
Dan Gohman193c2352008-06-02 21:30:49 +0000391 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
392 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
Chris Lattner9d1af972004-05-28 05:47:27 +0000393 ++RenameCounter;
Chris Lattner68758072004-05-09 06:20:51 +0000394 Changed = true;
395 }
Chris Lattnerf9a05322006-02-13 22:22:42 +0000396
397
398 // Loop over all external functions and globals. If we have two with
399 // identical names, merge them.
400 // FIXME: This code should disappear when we don't allow values with the same
401 // names when they have different types!
402 std::map<std::string, GlobalValue*> ExtSymbols;
403 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
404 Function *GV = I++;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000405 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerf9a05322006-02-13 22:22:42 +0000406 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
407 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
408 if (!X.second) {
409 // Found a conflict, replace this global with the previous one.
410 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000411 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000412 GV->eraseFromParent();
413 Changed = true;
414 }
415 }
416 }
417 // Do the same for globals.
418 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
419 I != E;) {
420 GlobalVariable *GV = I++;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000421 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerf9a05322006-02-13 22:22:42 +0000422 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
423 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
424 if (!X.second) {
425 // Found a conflict, replace this global with the previous one.
426 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000427 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000428 GV->eraseFromParent();
429 Changed = true;
430 }
431 }
432 }
433
Chris Lattner68758072004-05-09 06:20:51 +0000434 return Changed;
435}
436
Chris Lattner0c54d892006-05-23 23:39:48 +0000437/// printStructReturnPointerFunctionType - This is like printType for a struct
438/// return type, except, instead of printing the type as void (*)(Struct*, ...)
439/// print it as "Struct (*)(...)", for struct return functions.
David Greene71847812009-07-14 20:18:05 +0000440void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
Devang Patel05988662008-09-25 21:00:45 +0000441 const AttrListPtr &PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +0000442 const PointerType *TheTy) {
443 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
444 std::stringstream FunctionInnards;
445 FunctionInnards << " (*) (";
446 bool PrintedType = false;
447
448 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
449 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
Reid Spencer0ae96932007-01-07 03:24:48 +0000450 unsigned Idx = 1;
Evan Cheng681d2b82008-01-11 03:07:46 +0000451 for (++I, ++Idx; I != E; ++I, ++Idx) {
Chris Lattner0c54d892006-05-23 23:39:48 +0000452 if (PrintedType)
453 FunctionInnards << ", ";
Evan Cheng681d2b82008-01-11 03:07:46 +0000454 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000455 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng588c6f82008-01-11 09:12:49 +0000456 assert(isa<PointerType>(ArgTy));
457 ArgTy = cast<PointerType>(ArgTy)->getElementType();
458 }
Evan Cheng681d2b82008-01-11 03:07:46 +0000459 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000460 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Chris Lattner0c54d892006-05-23 23:39:48 +0000461 PrintedType = true;
462 }
463 if (FTy->isVarArg()) {
464 if (PrintedType)
465 FunctionInnards << ", ...";
466 } else if (!PrintedType) {
467 FunctionInnards << "void";
468 }
469 FunctionInnards << ')';
470 std::string tstr = FunctionInnards.str();
Reid Spencer0ae96932007-01-07 03:24:48 +0000471 printType(Out, RetTy,
Devang Patel05988662008-09-25 21:00:45 +0000472 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Chris Lattner0c54d892006-05-23 23:39:48 +0000473}
474
Owen Andersoncb371882008-08-21 00:14:44 +0000475raw_ostream &
David Greene71847812009-07-14 20:18:05 +0000476CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
477 bool isSigned,
Owen Andersoncb371882008-08-21 00:14:44 +0000478 const std::string &NameSoFar) {
479 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
480 "Invalid type for printSimpleType");
481 switch (Ty->getTypeID()) {
482 case Type::VoidTyID: return Out << "void " << NameSoFar;
483 case Type::IntegerTyID: {
484 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
485 if (NumBits == 1)
486 return Out << "bool " << NameSoFar;
487 else if (NumBits <= 8)
488 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
489 else if (NumBits <= 16)
490 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
491 else if (NumBits <= 32)
492 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
493 else if (NumBits <= 64)
494 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
495 else {
496 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
497 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
498 }
499 }
500 case Type::FloatTyID: return Out << "float " << NameSoFar;
501 case Type::DoubleTyID: return Out << "double " << NameSoFar;
502 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
503 // present matches host 'long double'.
504 case Type::X86_FP80TyID:
505 case Type::PPC_FP128TyID:
506 case Type::FP128TyID: return Out << "long double " << NameSoFar;
507
508 case Type::VectorTyID: {
509 const VectorType *VTy = cast<VectorType>(Ty);
510 return printSimpleType(Out, VTy->getElementType(), isSigned,
511 " __attribute__((vector_size(" +
Duncan Sands777d2302009-05-09 07:06:46 +0000512 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Owen Andersoncb371882008-08-21 00:14:44 +0000513 }
514
515 default:
Torok Edwindac237e2009-07-08 20:53:28 +0000516#ifndef NDEBUG
Owen Andersoncb371882008-08-21 00:14:44 +0000517 cerr << "Unknown primitive type: " << *Ty << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +0000518#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000519 llvm_unreachable(0);
Owen Andersoncb371882008-08-21 00:14:44 +0000520 }
521}
522
Reid Spencere4d87aa2006-12-23 06:05:41 +0000523std::ostream &
Reid Spencera54b7cb2007-01-12 07:05:14 +0000524CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
Chris Lattner90683ab2008-03-02 03:41:23 +0000525 const std::string &NameSoFar) {
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000526 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
Reid Spencera54b7cb2007-01-12 07:05:14 +0000527 "Invalid type for printSimpleType");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000528 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000529 case Type::VoidTyID: return Out << "void " << NameSoFar;
530 case Type::IntegerTyID: {
531 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
532 if (NumBits == 1)
533 return Out << "bool " << NameSoFar;
534 else if (NumBits <= 8)
535 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
536 else if (NumBits <= 16)
537 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
538 else if (NumBits <= 32)
539 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
Dan Gohmand7614802008-04-02 19:40:14 +0000540 else if (NumBits <= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000541 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
Dan Gohmand7614802008-04-02 19:40:14 +0000542 else {
543 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
544 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000545 }
546 }
547 case Type::FloatTyID: return Out << "float " << NameSoFar;
548 case Type::DoubleTyID: return Out << "double " << NameSoFar;
Dale Johannesen53f0bc12007-09-17 00:38:27 +0000549 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
550 // present matches host 'long double'.
551 case Type::X86_FP80TyID:
552 case Type::PPC_FP128TyID:
553 case Type::FP128TyID: return Out << "long double " << NameSoFar;
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000554
555 case Type::VectorTyID: {
556 const VectorType *VTy = cast<VectorType>(Ty);
Chris Lattner90683ab2008-03-02 03:41:23 +0000557 return printSimpleType(Out, VTy->getElementType(), isSigned,
Chris Lattner32cba8e2008-03-02 03:39:43 +0000558 " __attribute__((vector_size(" +
Duncan Sands777d2302009-05-09 07:06:46 +0000559 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000560 }
561
562 default:
Torok Edwindac237e2009-07-08 20:53:28 +0000563#ifndef NDEBUG
Reid Spencere4d87aa2006-12-23 06:05:41 +0000564 cerr << "Unknown primitive type: " << *Ty << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +0000565#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000566 llvm_unreachable(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000567 }
568}
Chris Lattner68758072004-05-09 06:20:51 +0000569
Chris Lattner83c57752002-08-19 22:17:53 +0000570// Pass the Type* and the variable name and this prints out the variable
571// declaration.
572//
David Greene71847812009-07-14 20:18:05 +0000573raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
574 const Type *Ty,
575 bool isSigned, const std::string &NameSoFar,
576 bool IgnoreName, const AttrListPtr &PAL) {
Owen Andersoncb371882008-08-21 00:14:44 +0000577 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
578 printSimpleType(Out, Ty, isSigned, NameSoFar);
579 return Out;
580 }
581
582 // Check to see if the type is named.
583 if (!IgnoreName || isa<OpaqueType>(Ty)) {
584 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
585 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
586 }
587
588 switch (Ty->getTypeID()) {
589 case Type::FunctionTyID: {
590 const FunctionType *FTy = cast<FunctionType>(Ty);
591 std::stringstream FunctionInnards;
592 FunctionInnards << " (" << NameSoFar << ") (";
593 unsigned Idx = 1;
594 for (FunctionType::param_iterator I = FTy->param_begin(),
595 E = FTy->param_end(); I != E; ++I) {
596 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000597 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Owen Andersoncb371882008-08-21 00:14:44 +0000598 assert(isa<PointerType>(ArgTy));
599 ArgTy = cast<PointerType>(ArgTy)->getElementType();
600 }
601 if (I != FTy->param_begin())
602 FunctionInnards << ", ";
603 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000604 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Owen Andersoncb371882008-08-21 00:14:44 +0000605 ++Idx;
606 }
607 if (FTy->isVarArg()) {
608 if (FTy->getNumParams())
609 FunctionInnards << ", ...";
610 } else if (!FTy->getNumParams()) {
611 FunctionInnards << "void";
612 }
613 FunctionInnards << ')';
614 std::string tstr = FunctionInnards.str();
615 printType(Out, FTy->getReturnType(),
Devang Patel05988662008-09-25 21:00:45 +0000616 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Owen Andersoncb371882008-08-21 00:14:44 +0000617 return Out;
618 }
619 case Type::StructTyID: {
620 const StructType *STy = cast<StructType>(Ty);
621 Out << NameSoFar + " {\n";
622 unsigned Idx = 0;
623 for (StructType::element_iterator I = STy->element_begin(),
624 E = STy->element_end(); I != E; ++I) {
625 Out << " ";
626 printType(Out, *I, false, "field" + utostr(Idx++));
627 Out << ";\n";
628 }
629 Out << '}';
630 if (STy->isPacked())
631 Out << " __attribute__ ((packed))";
632 return Out;
633 }
634
635 case Type::PointerTyID: {
636 const PointerType *PTy = cast<PointerType>(Ty);
637 std::string ptrName = "*" + NameSoFar;
638
639 if (isa<ArrayType>(PTy->getElementType()) ||
640 isa<VectorType>(PTy->getElementType()))
641 ptrName = "(" + ptrName + ")";
642
643 if (!PAL.isEmpty())
644 // Must be a function ptr cast!
645 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
646 return printType(Out, PTy->getElementType(), false, ptrName);
647 }
648
649 case Type::ArrayTyID: {
650 const ArrayType *ATy = cast<ArrayType>(Ty);
651 unsigned NumElements = ATy->getNumElements();
652 if (NumElements == 0) NumElements = 1;
653 // Arrays are wrapped in structs to allow them to have normal
654 // value semantics (avoiding the array "decay").
655 Out << NameSoFar << " { ";
656 printType(Out, ATy->getElementType(), false,
657 "array[" + utostr(NumElements) + "]");
658 return Out << "; }";
659 }
660
661 case Type::OpaqueTyID: {
Owen Anderson52132bf2009-06-26 19:48:37 +0000662 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Owen Andersoncb371882008-08-21 00:14:44 +0000663 assert(TypeNames.find(Ty) == TypeNames.end());
664 TypeNames[Ty] = TyName;
665 return Out << TyName << ' ' << NameSoFar;
666 }
667 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000668 llvm_unreachable("Unhandled case in getTypeProps!");
Owen Andersoncb371882008-08-21 00:14:44 +0000669 }
670
671 return Out;
672}
673
674// Pass the Type* and the variable name and this prints out the variable
675// declaration.
676//
Chris Lattneredd8ce12003-05-03 03:14:35 +0000677std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
Reid Spencer0ae96932007-01-07 03:24:48 +0000678 bool isSigned, const std::string &NameSoFar,
Devang Patel05988662008-09-25 21:00:45 +0000679 bool IgnoreName, const AttrListPtr &PAL) {
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000680 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000681 printSimpleType(Out, Ty, isSigned, NameSoFar);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000682 return Out;
683 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000684
Chris Lattner83c57752002-08-19 22:17:53 +0000685 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000686 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +0000687 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000688 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000689 }
Chris Lattner83c57752002-08-19 22:17:53 +0000690
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000691 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000692 case Type::FunctionTyID: {
Chris Lattner0c54d892006-05-23 23:39:48 +0000693 const FunctionType *FTy = cast<FunctionType>(Ty);
Misha Brukmand6a29a52005-04-20 16:05:03 +0000694 std::stringstream FunctionInnards;
Joel Stanley54f60322003-06-25 04:52:09 +0000695 FunctionInnards << " (" << NameSoFar << ") (";
Reid Spencer0ae96932007-01-07 03:24:48 +0000696 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +0000697 for (FunctionType::param_iterator I = FTy->param_begin(),
698 E = FTy->param_end(); I != E; ++I) {
Evan Cheng7723ab32008-01-12 18:53:07 +0000699 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000700 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng7723ab32008-01-12 18:53:07 +0000701 assert(isa<PointerType>(ArgTy));
702 ArgTy = cast<PointerType>(ArgTy)->getElementType();
703 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000704 if (I != FTy->param_begin())
Joel Stanley54f60322003-06-25 04:52:09 +0000705 FunctionInnards << ", ";
Evan Cheng7723ab32008-01-12 18:53:07 +0000706 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000707 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Reid Spencer0ae96932007-01-07 03:24:48 +0000708 ++Idx;
Chris Lattner83c57752002-08-19 22:17:53 +0000709 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000710 if (FTy->isVarArg()) {
711 if (FTy->getNumParams())
Reid Spencer9231ac82004-05-25 08:53:40 +0000712 FunctionInnards << ", ...";
Chris Lattner0c54d892006-05-23 23:39:48 +0000713 } else if (!FTy->getNumParams()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000714 FunctionInnards << "void";
Chris Lattner83c57752002-08-19 22:17:53 +0000715 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000716 FunctionInnards << ')';
Joel Stanley54f60322003-06-25 04:52:09 +0000717 std::string tstr = FunctionInnards.str();
Reid Spencer0ae96932007-01-07 03:24:48 +0000718 printType(Out, FTy->getReturnType(),
Devang Patel05988662008-09-25 21:00:45 +0000719 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000720 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000721 }
722 case Type::StructTyID: {
723 const StructType *STy = cast<StructType>(Ty);
724 Out << NameSoFar + " {\n";
725 unsigned Idx = 0;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000726 for (StructType::element_iterator I = STy->element_begin(),
727 E = STy->element_end(); I != E; ++I) {
Chris Lattner83c57752002-08-19 22:17:53 +0000728 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +0000729 printType(Out, *I, false, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000730 Out << ";\n";
731 }
Lauro Ramos Venancioa126bb72007-07-11 19:56:53 +0000732 Out << '}';
733 if (STy->isPacked())
734 Out << " __attribute__ ((packed))";
735 return Out;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000736 }
Chris Lattner83c57752002-08-19 22:17:53 +0000737
738 case Type::PointerTyID: {
739 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000740 std::string ptrName = "*" + NameSoFar;
741
Robert Bocchinob78e8382006-01-20 20:43:57 +0000742 if (isa<ArrayType>(PTy->getElementType()) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +0000743 isa<VectorType>(PTy->getElementType()))
Chris Lattner8917d362003-11-03 04:31:54 +0000744 ptrName = "(" + ptrName + ")";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000745
Chris Lattner58d74912008-03-12 17:45:29 +0000746 if (!PAL.isEmpty())
Evan Cheng7723ab32008-01-12 18:53:07 +0000747 // Must be a function ptr cast!
748 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
Reid Spencer251f2142007-01-09 17:09:09 +0000749 return printType(Out, PTy->getElementType(), false, ptrName);
Misha Brukman8f9f9a22003-07-21 16:34:35 +0000750 }
Chris Lattner83c57752002-08-19 22:17:53 +0000751
752 case Type::ArrayTyID: {
753 const ArrayType *ATy = cast<ArrayType>(Ty);
754 unsigned NumElements = ATy->getNumElements();
Chris Lattner3e3b6f72004-12-15 23:13:15 +0000755 if (NumElements == 0) NumElements = 1;
Dan Gohman193c2352008-06-02 21:30:49 +0000756 // Arrays are wrapped in structs to allow them to have normal
757 // value semantics (avoiding the array "decay").
758 Out << NameSoFar << " { ";
759 printType(Out, ATy->getElementType(), false,
760 "array[" + utostr(NumElements) + "]");
761 return Out << "; }";
Chris Lattner83c57752002-08-19 22:17:53 +0000762 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000763
764 case Type::OpaqueTyID: {
Owen Anderson52132bf2009-06-26 19:48:37 +0000765 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Chris Lattner04b72c82002-10-16 00:08:22 +0000766 assert(TypeNames.find(Ty) == TypeNames.end());
767 TypeNames[Ty] = TyName;
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000768 return Out << TyName << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000769 }
Chris Lattner83c57752002-08-19 22:17:53 +0000770 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000771 llvm_unreachable("Unhandled case in getTypeProps!");
Chris Lattner83c57752002-08-19 22:17:53 +0000772 }
773
774 return Out;
775}
776
Dan Gohman9f8d5712008-07-24 17:57:48 +0000777void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
Chris Lattner6d492922002-08-19 21:32:41 +0000778
779 // As a special case, print the array as a string if it is an array of
780 // ubytes or an array of sbytes with positive values.
Misha Brukmand6a29a52005-04-20 16:05:03 +0000781 //
Chris Lattner6d492922002-08-19 21:32:41 +0000782 const Type *ETy = CPA->getType()->getElementType();
Reid Spencer47857812006-12-31 05:55:36 +0000783 bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty);
Chris Lattner6d492922002-08-19 21:32:41 +0000784
785 // Make sure the last character is a null char, as automatically added by C
Chris Lattner02da6c02003-06-16 12:09:09 +0000786 if (isString && (CPA->getNumOperands() == 0 ||
787 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattner6d492922002-08-19 21:32:41 +0000788 isString = false;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000789
Chris Lattner6d492922002-08-19 21:32:41 +0000790 if (isString) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000791 Out << '\"';
Chris Lattner02da6c02003-06-16 12:09:09 +0000792 // Keep track of whether the last number was a hexadecimal escape
793 bool LastWasHex = false;
794
Chris Lattner6d492922002-08-19 21:32:41 +0000795 // Do not include the last character, which we know is null
796 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000797 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000798
Chris Lattner02da6c02003-06-16 12:09:09 +0000799 // Print it out literally if it is a printable character. The only thing
800 // to be careful about is when the last letter output was a hex escape
801 // code, in which case we have to be careful not to print out hex digits
Chris Lattnerda920902003-06-16 12:21:19 +0000802 // explicitly (the C compiler thinks it is a continuation of the previous
803 // character, sheesh...)
Chris Lattner02da6c02003-06-16 12:09:09 +0000804 //
805 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
806 LastWasHex = false;
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000807 if (C == '"' || C == '\\')
Chris Lattner1f0f37a2008-08-21 05:51:43 +0000808 Out << "\\" << (char)C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000809 else
Chris Lattner1f0f37a2008-08-21 05:51:43 +0000810 Out << (char)C;
Chris Lattner6d492922002-08-19 21:32:41 +0000811 } else {
Chris Lattner02da6c02003-06-16 12:09:09 +0000812 LastWasHex = false;
Chris Lattner6d492922002-08-19 21:32:41 +0000813 switch (C) {
814 case '\n': Out << "\\n"; break;
815 case '\t': Out << "\\t"; break;
816 case '\r': Out << "\\r"; break;
817 case '\v': Out << "\\v"; break;
818 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000819 case '\"': Out << "\\\""; break;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000820 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000821 default:
822 Out << "\\x";
Chris Lattner02da6c02003-06-16 12:09:09 +0000823 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
824 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
825 LastWasHex = true;
Chris Lattner6d492922002-08-19 21:32:41 +0000826 break;
827 }
828 }
829 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000830 Out << '\"';
Chris Lattner6d492922002-08-19 21:32:41 +0000831 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000832 Out << '{';
Chris Lattner6d492922002-08-19 21:32:41 +0000833 if (CPA->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000834 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000835 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000836 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
837 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +0000838 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000839 }
840 }
841 Out << " }";
842 }
843}
844
Dan Gohman9f8d5712008-07-24 17:57:48 +0000845void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
Robert Bocchinob78e8382006-01-20 20:43:57 +0000846 Out << '{';
847 if (CP->getNumOperands()) {
848 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000849 printConstant(cast<Constant>(CP->getOperand(0)), Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000850 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
851 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +0000852 printConstant(cast<Constant>(CP->getOperand(i)), Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000853 }
854 }
855 Out << " }";
856}
857
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000858// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
859// textually as a double (rather than as a reference to a stack-allocated
860// variable). We decide this by converting CFP to a string and back into a
861// double, and then checking whether the conversion results in a bit-equal
862// double to the original value of CFP. This depends on us and the target C
863// compiler agreeing on the conversion process (which is pretty likely since we
864// only deal in IEEE FP).
865//
Chris Lattnercb3ad012004-05-09 20:41:32 +0000866static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Dale Johannesen23a98552008-10-09 23:00:39 +0000867 bool ignored;
Dale Johannesen53f0bc12007-09-17 00:38:27 +0000868 // Do long doubles in hex for now.
Chris Lattneraecc22a2008-10-22 04:53:16 +0000869 if (CFP->getType() != Type::FloatTy && CFP->getType() != Type::DoubleTy)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000870 return false;
Dale Johannesen43421b32007-09-06 18:13:44 +0000871 APFloat APF = APFloat(CFP->getValueAPF()); // copy
Chris Lattneraecc22a2008-10-22 04:53:16 +0000872 if (CFP->getType() == Type::FloatTy)
Dale Johannesen23a98552008-10-09 23:00:39 +0000873 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Reid Spencerbcf81242006-11-05 19:26:37 +0000874#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000875 char Buffer[100];
Dale Johannesen43421b32007-09-06 18:13:44 +0000876 sprintf(Buffer, "%a", APF.convertToDouble());
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000877 if (!strncmp(Buffer, "0x", 2) ||
878 !strncmp(Buffer, "-0x", 3) ||
879 !strncmp(Buffer, "+0x", 3))
Dale Johannesen43421b32007-09-06 18:13:44 +0000880 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000881 return false;
882#else
Dale Johannesen43421b32007-09-06 18:13:44 +0000883 std::string StrVal = ftostr(APF);
Chris Lattner9860e772003-10-12 04:36:29 +0000884
885 while (StrVal[0] == ' ')
886 StrVal.erase(StrVal.begin());
887
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000888 // Check to make sure that the stringized number is not some string like "Inf"
889 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaekeb471a232003-06-17 23:55:35 +0000890 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
891 ((StrVal[0] == '-' || StrVal[0] == '+') &&
892 (StrVal[1] >= '0' && StrVal[1] <= '9')))
893 // Reparse stringized version!
Dale Johannesen43421b32007-09-06 18:13:44 +0000894 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
Brian Gaekeb471a232003-06-17 23:55:35 +0000895 return false;
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000896#endif
Brian Gaekeb471a232003-06-17 23:55:35 +0000897}
Chris Lattner6d492922002-08-19 21:32:41 +0000898
Reid Spencer3da59db2006-11-27 01:05:10 +0000899/// Print out the casting for a cast operation. This does the double casting
900/// necessary for conversion to the destination type, if necessary.
Reid Spencer3da59db2006-11-27 01:05:10 +0000901/// @brief Print a cast
902void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000903 // Print the destination type cast
904 switch (opc) {
905 case Instruction::UIToFP:
906 case Instruction::SIToFP:
907 case Instruction::IntToPtr:
908 case Instruction::Trunc:
909 case Instruction::BitCast:
910 case Instruction::FPExt:
911 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
912 Out << '(';
913 printType(Out, DstTy);
914 Out << ')';
915 break;
916 case Instruction::ZExt:
917 case Instruction::PtrToInt:
918 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
919 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000920 printSimpleType(Out, DstTy, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000921 Out << ')';
922 break;
923 case Instruction::SExt:
924 case Instruction::FPToSI: // For these, make sure we get a signed dest
925 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000926 printSimpleType(Out, DstTy, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000927 Out << ')';
928 break;
929 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000930 llvm_unreachable("Invalid cast opcode");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000931 }
932
933 // Print the source type cast
Reid Spencer3da59db2006-11-27 01:05:10 +0000934 switch (opc) {
935 case Instruction::UIToFP:
936 case Instruction::ZExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000937 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000938 printSimpleType(Out, SrcTy, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000939 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000940 break;
941 case Instruction::SIToFP:
942 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000943 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000944 printSimpleType(Out, SrcTy, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000945 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000946 break;
947 case Instruction::IntToPtr:
948 case Instruction::PtrToInt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000949 // Avoid "cast to pointer from integer of different size" warnings
950 Out << "(unsigned long)";
951 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000952 case Instruction::Trunc:
953 case Instruction::BitCast:
954 case Instruction::FPExt:
955 case Instruction::FPTrunc:
956 case Instruction::FPToSI:
957 case Instruction::FPToUI:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000958 break; // These don't need a source cast.
Reid Spencer3da59db2006-11-27 01:05:10 +0000959 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000960 llvm_unreachable("Invalid cast opcode");
Reid Spencer3da59db2006-11-27 01:05:10 +0000961 break;
962 }
963}
964
Chris Lattner6d492922002-08-19 21:32:41 +0000965// printConstant - The LLVM Constant to C Constant converter.
Dan Gohman9f8d5712008-07-24 17:57:48 +0000966void CWriter::printConstant(Constant *CPV, bool Static) {
Chris Lattner6d492922002-08-19 21:32:41 +0000967 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
968 switch (CE->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000969 case Instruction::Trunc:
970 case Instruction::ZExt:
971 case Instruction::SExt:
972 case Instruction::FPTrunc:
973 case Instruction::FPExt:
974 case Instruction::UIToFP:
975 case Instruction::SIToFP:
976 case Instruction::FPToUI:
977 case Instruction::FPToSI:
978 case Instruction::PtrToInt:
979 case Instruction::IntToPtr:
980 case Instruction::BitCast:
981 Out << "(";
982 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
Chris Lattner72623362007-05-03 02:57:13 +0000983 if (CE->getOpcode() == Instruction::SExt &&
984 CE->getOperand(0)->getType() == Type::Int1Ty) {
Reid Spencercee7ba32007-05-02 02:17:41 +0000985 // Make sure we really sext from bool here by subtracting from 0
986 Out << "0-";
Reid Spencercee7ba32007-05-02 02:17:41 +0000987 }
Dan Gohman9f8d5712008-07-24 17:57:48 +0000988 printConstant(CE->getOperand(0), Static);
Chris Lattner72623362007-05-03 02:57:13 +0000989 if (CE->getType() == Type::Int1Ty &&
990 (CE->getOpcode() == Instruction::Trunc ||
991 CE->getOpcode() == Instruction::FPToUI ||
992 CE->getOpcode() == Instruction::FPToSI ||
993 CE->getOpcode() == Instruction::PtrToInt)) {
994 // Make sure we really truncate to bool here by anding with 1
995 Out << "&1u";
996 }
997 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000998 return;
Chris Lattner72623362007-05-03 02:57:13 +0000999
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001000 case Instruction::GetElementPtr:
Chris Lattnere05252b42008-03-02 08:07:24 +00001001 Out << "(";
1002 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
Dan Gohman9f8d5712008-07-24 17:57:48 +00001003 gep_type_end(CPV), Static);
Chris Lattnere05252b42008-03-02 08:07:24 +00001004 Out << ")";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001005 return;
Chris Lattner6683dbf2004-04-01 05:28:26 +00001006 case Instruction::Select:
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001007 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001008 printConstant(CE->getOperand(0), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001009 Out << '?';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001010 printConstant(CE->getOperand(1), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001011 Out << ':';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001012 printConstant(CE->getOperand(2), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001013 Out << ')';
Chris Lattner6683dbf2004-04-01 05:28:26 +00001014 return;
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001015 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001016 case Instruction::FAdd:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001017 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001018 case Instruction::FSub:
Chris Lattner29255922003-08-14 19:19:53 +00001019 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001020 case Instruction::FMul:
Reid Spencer1628cec2006-10-26 06:15:43 +00001021 case Instruction::SDiv:
1022 case Instruction::UDiv:
1023 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001024 case Instruction::URem:
1025 case Instruction::SRem:
1026 case Instruction::FRem:
Chris Lattnerf376e5e2004-12-29 04:00:09 +00001027 case Instruction::And:
1028 case Instruction::Or:
1029 case Instruction::Xor:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001030 case Instruction::ICmp:
Brian Gaeke0415b6c2003-11-22 05:02:56 +00001031 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001032 case Instruction::LShr:
1033 case Instruction::AShr:
Reid Spencer72ddc212006-10-26 06:17:40 +00001034 {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001035 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001036 bool NeedsClosingParens = printConstExprCast(CE, Static);
Reid Spencer1628cec2006-10-26 06:15:43 +00001037 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
Chris Lattner29255922003-08-14 19:19:53 +00001038 switch (CE->getOpcode()) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001039 case Instruction::Add:
1040 case Instruction::FAdd: Out << " + "; break;
1041 case Instruction::Sub:
1042 case Instruction::FSub: Out << " - "; break;
1043 case Instruction::Mul:
1044 case Instruction::FMul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001045 case Instruction::URem:
1046 case Instruction::SRem:
1047 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001048 case Instruction::UDiv:
1049 case Instruction::SDiv:
1050 case Instruction::FDiv: Out << " / "; break;
Chris Lattnerf376e5e2004-12-29 04:00:09 +00001051 case Instruction::And: Out << " & "; break;
1052 case Instruction::Or: Out << " | "; break;
1053 case Instruction::Xor: Out << " ^ "; break;
Brian Gaeke0415b6c2003-11-22 05:02:56 +00001054 case Instruction::Shl: Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001055 case Instruction::LShr:
1056 case Instruction::AShr: Out << " >> "; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001057 case Instruction::ICmp:
1058 switch (CE->getPredicate()) {
1059 case ICmpInst::ICMP_EQ: Out << " == "; break;
1060 case ICmpInst::ICMP_NE: Out << " != "; break;
1061 case ICmpInst::ICMP_SLT:
1062 case ICmpInst::ICMP_ULT: Out << " < "; break;
1063 case ICmpInst::ICMP_SLE:
1064 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1065 case ICmpInst::ICMP_SGT:
1066 case ICmpInst::ICMP_UGT: Out << " > "; break;
1067 case ICmpInst::ICMP_SGE:
1068 case ICmpInst::ICMP_UGE: Out << " >= "; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00001069 default: llvm_unreachable("Illegal ICmp predicate");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001070 }
1071 break;
Torok Edwinc23197a2009-07-14 16:55:14 +00001072 default: llvm_unreachable("Illegal opcode here!");
Chris Lattner29255922003-08-14 19:19:53 +00001073 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001074 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1075 if (NeedsClosingParens)
1076 Out << "))";
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001077 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001078 return;
Reid Spencer72ddc212006-10-26 06:17:40 +00001079 }
Reid Spencerb801a272007-01-08 06:58:32 +00001080 case Instruction::FCmp: {
1081 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001082 bool NeedsClosingParens = printConstExprCast(CE, Static);
Reid Spencerb801a272007-01-08 06:58:32 +00001083 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1084 Out << "0";
1085 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1086 Out << "1";
1087 else {
1088 const char* op = 0;
1089 switch (CE->getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001090 default: llvm_unreachable("Illegal FCmp predicate");
Reid Spencerb801a272007-01-08 06:58:32 +00001091 case FCmpInst::FCMP_ORD: op = "ord"; break;
1092 case FCmpInst::FCMP_UNO: op = "uno"; break;
1093 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1094 case FCmpInst::FCMP_UNE: op = "une"; break;
1095 case FCmpInst::FCMP_ULT: op = "ult"; break;
1096 case FCmpInst::FCMP_ULE: op = "ule"; break;
1097 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1098 case FCmpInst::FCMP_UGE: op = "uge"; break;
1099 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1100 case FCmpInst::FCMP_ONE: op = "one"; break;
1101 case FCmpInst::FCMP_OLT: op = "olt"; break;
1102 case FCmpInst::FCMP_OLE: op = "ole"; break;
1103 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1104 case FCmpInst::FCMP_OGE: op = "oge"; break;
1105 }
1106 Out << "llvm_fcmp_" << op << "(";
1107 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1108 Out << ", ";
1109 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1110 Out << ")";
1111 }
1112 if (NeedsClosingParens)
1113 Out << "))";
1114 Out << ')';
Anton Korobeynikovdceadaf2007-12-21 23:33:44 +00001115 return;
Reid Spencerb801a272007-01-08 06:58:32 +00001116 }
Chris Lattner6d492922002-08-19 21:32:41 +00001117 default:
Torok Edwindac237e2009-07-08 20:53:28 +00001118#ifndef NDEBUG
Bill Wendlingf5da1332006-12-07 22:21:48 +00001119 cerr << "CWriter Error: Unhandled constant expression: "
1120 << *CE << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +00001121#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001122 llvm_unreachable(0);
Chris Lattner6d492922002-08-19 21:32:41 +00001123 }
Dan Gohman17dab192008-05-23 16:57:00 +00001124 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
Chris Lattner665825e2004-10-17 17:48:59 +00001125 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +00001126 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnerd9a706e2008-03-02 08:14:45 +00001127 Out << ")/*UNDEF*/";
1128 if (!isa<VectorType>(CPV->getType())) {
1129 Out << "0)";
1130 } else {
1131 Out << "{})";
1132 }
Chris Lattnera9d12c02004-10-16 18:12:13 +00001133 return;
Chris Lattner6d492922002-08-19 21:32:41 +00001134 }
1135
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001136 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1137 const Type* Ty = CI->getType();
Reid Spencer4fe16d62007-01-11 18:21:29 +00001138 if (Ty == Type::Int1Ty)
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001139 Out << (CI->getZExtValue() ? '1' : '0');
1140 else if (Ty == Type::Int32Ty)
1141 Out << CI->getZExtValue() << 'u';
1142 else if (Ty->getPrimitiveSizeInBits() > 32)
1143 Out << CI->getZExtValue() << "ull";
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001144 else {
1145 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001146 printSimpleType(Out, Ty, false) << ')';
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001147 if (CI->isMinValue(true))
1148 Out << CI->getZExtValue() << 'u';
1149 else
1150 Out << CI->getSExtValue();
Dale Johannesenf4786cc2009-05-19 00:46:42 +00001151 Out << ')';
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001152 }
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001153 return;
1154 }
1155
1156 switch (CPV->getType()->getTypeID()) {
Chris Lattner6d492922002-08-19 21:32:41 +00001157 case Type::FloatTyID:
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001158 case Type::DoubleTyID:
1159 case Type::X86_FP80TyID:
1160 case Type::PPC_FP128TyID:
1161 case Type::FP128TyID: {
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001162 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattneredd8ce12003-05-03 03:14:35 +00001163 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001164 if (I != FPConstantMap.end()) {
1165 // Because of FP precision problems we must load from a stack allocated
1166 // value that holds the value in hex.
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001167 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" :
1168 FPC->getType() == Type::DoubleTy ? "double" :
1169 "long double")
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001170 << "*)&FPConstant" << I->second << ')';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001171 } else {
Chris Lattnerabec4742008-10-17 06:11:48 +00001172 double V;
1173 if (FPC->getType() == Type::FloatTy)
1174 V = FPC->getValueAPF().convertToFloat();
1175 else if (FPC->getType() == Type::DoubleTy)
1176 V = FPC->getValueAPF().convertToDouble();
1177 else {
1178 // Long double. Convert the number to double, discarding precision.
1179 // This is not awesome, but it at least makes the CBE output somewhat
1180 // useful.
1181 APFloat Tmp = FPC->getValueAPF();
1182 bool LosesInfo;
1183 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1184 V = Tmp.convertToDouble();
1185 }
1186
Dale Johannesen43421b32007-09-06 18:13:44 +00001187 if (IsNAN(V)) {
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001188 // The value is NaN
Misha Brukmand6a29a52005-04-20 16:05:03 +00001189
Dale Johannesen43421b32007-09-06 18:13:44 +00001190 // FIXME the actual NaN bits should be emitted.
Brian Gaeke8a702e82004-08-25 19:00:42 +00001191 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1192 // it's 0x7ff4.
1193 const unsigned long QuietNaN = 0x7ff8UL;
Reid Spencer3ed469c2006-11-02 20:25:50 +00001194 //const unsigned long SignalNaN = 0x7ff4UL;
Brian Gaeke8a702e82004-08-25 19:00:42 +00001195
1196 // We need to grab the first part of the FP #
Brian Gaeke8a702e82004-08-25 19:00:42 +00001197 char Buffer[100];
1198
Dale Johannesen43421b32007-09-06 18:13:44 +00001199 uint64_t ll = DoubleToBits(V);
Reid Spencer2bc320d2006-05-31 22:26:11 +00001200 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
Brian Gaeke8a702e82004-08-25 19:00:42 +00001201
1202 std::string Num(&Buffer[0], &Buffer[6]);
1203 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1204
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001205 if (FPC->getType() == Type::FloatTy)
Brian Gaeke8a702e82004-08-25 19:00:42 +00001206 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1207 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001208 else
Brian Gaeke8a702e82004-08-25 19:00:42 +00001209 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1210 << Buffer << "\") /*nan*/ ";
Dale Johannesen43421b32007-09-06 18:13:44 +00001211 } else if (IsInf(V)) {
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001212 // The value is Inf
Dale Johannesen43421b32007-09-06 18:13:44 +00001213 if (V < 0) Out << '-';
Brian Gaeke8a702e82004-08-25 19:00:42 +00001214 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
1215 << " /*inf*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001216 } else {
Brian Gaeke07b52b32004-08-25 19:37:26 +00001217 std::string Num;
Reid Spencerbcf81242006-11-05 19:26:37 +00001218#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Brian Gaeke07b52b32004-08-25 19:37:26 +00001219 // Print out the constant as a floating point number.
1220 char Buffer[100];
Dale Johannesen43421b32007-09-06 18:13:44 +00001221 sprintf(Buffer, "%a", V);
Brian Gaeke07b52b32004-08-25 19:37:26 +00001222 Num = Buffer;
1223#else
Dale Johannesen43421b32007-09-06 18:13:44 +00001224 Num = ftostr(FPC->getValueAPF());
Brian Gaeke07b52b32004-08-25 19:37:26 +00001225#endif
Dale Johannesen43421b32007-09-06 18:13:44 +00001226 Out << Num;
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001227 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001228 }
1229 break;
1230 }
Chris Lattner6d492922002-08-19 21:32:41 +00001231
1232 case Type::ArrayTyID:
Dan Gohman1a245392008-07-23 18:41:03 +00001233 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001234 if (!Static) {
1235 Out << "(";
1236 printType(Out, CPV->getType());
1237 Out << ")";
1238 }
Dan Gohman193c2352008-06-02 21:30:49 +00001239 Out << "{ "; // Arrays are wrapped in struct types.
Chris Lattner939732a2008-03-02 05:46:57 +00001240 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001241 printConstantArray(CA, Static);
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001242 } else {
1243 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001244 const ArrayType *AT = cast<ArrayType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001245 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001246 if (AT->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001247 Out << ' ';
Owen Anderson0a5372e2009-07-13 04:09:18 +00001248 Constant *CZ = Context->getNullValue(AT->getElementType());
Dan Gohman9f8d5712008-07-24 17:57:48 +00001249 printConstant(CZ, Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001250 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1251 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001252 printConstant(CZ, Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001253 }
1254 }
1255 Out << " }";
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001256 }
Dan Gohman193c2352008-06-02 21:30:49 +00001257 Out << " }"; // Arrays are wrapped in struct types.
Chris Lattner6d492922002-08-19 21:32:41 +00001258 break;
1259
Reid Spencer9d6565a2007-02-15 02:26:10 +00001260 case Type::VectorTyID:
Chris Lattner85feab62008-03-02 03:29:50 +00001261 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001262 if (!Static) {
1263 Out << "(";
1264 printType(Out, CPV->getType());
1265 Out << ")";
1266 }
Chris Lattner939732a2008-03-02 05:46:57 +00001267 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001268 printConstantVector(CV, Static);
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001269 } else {
1270 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1271 const VectorType *VT = cast<VectorType>(CPV->getType());
1272 Out << "{ ";
Owen Anderson0a5372e2009-07-13 04:09:18 +00001273 Constant *CZ = Context->getNullValue(VT->getElementType());
Dan Gohman9f8d5712008-07-24 17:57:48 +00001274 printConstant(CZ, Static);
Chris Lattner0a3d4d92008-03-02 03:18:46 +00001275 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001276 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001277 printConstant(CZ, Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +00001278 }
1279 Out << " }";
Robert Bocchinob78e8382006-01-20 20:43:57 +00001280 }
1281 break;
1282
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001283 case Type::StructTyID:
Dan Gohman1a245392008-07-23 18:41:03 +00001284 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001285 if (!Static) {
1286 Out << "(";
1287 printType(Out, CPV->getType());
1288 Out << ")";
1289 }
Chris Lattnera9d12c02004-10-16 18:12:13 +00001290 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001291 const StructType *ST = cast<StructType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001292 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001293 if (ST->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001294 Out << ' ';
Owen Anderson0a5372e2009-07-13 04:09:18 +00001295 printConstant(Context->getNullValue(ST->getElementType(0)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001296 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1297 Out << ", ";
Owen Anderson0a5372e2009-07-13 04:09:18 +00001298 printConstant(Context->getNullValue(ST->getElementType(i)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001299 }
Chris Lattner6d492922002-08-19 21:32:41 +00001300 }
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001301 Out << " }";
1302 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001303 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001304 if (CPV->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001305 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001306 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001307 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1308 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001309 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001310 }
1311 }
1312 Out << " }";
Chris Lattner6d492922002-08-19 21:32:41 +00001313 }
Chris Lattner6d492922002-08-19 21:32:41 +00001314 break;
Chris Lattner6d492922002-08-19 21:32:41 +00001315
1316 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001317 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattnercf135cb2003-06-02 03:10:53 +00001318 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +00001319 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnercf135cb2003-06-02 03:10:53 +00001320 Out << ")/*NULL*/0)";
Chris Lattner6d492922002-08-19 21:32:41 +00001321 break;
Reid Spencer518310c2004-07-18 00:44:37 +00001322 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001323 writeOperand(GV, Static);
Chris Lattner6d492922002-08-19 21:32:41 +00001324 break;
1325 }
1326 // FALL THROUGH
1327 default:
Torok Edwindac237e2009-07-08 20:53:28 +00001328#ifndef NDEBUG
Bill Wendlingf5da1332006-12-07 22:21:48 +00001329 cerr << "Unknown constant type: " << *CPV << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +00001330#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001331 llvm_unreachable(0);
Chris Lattner6d492922002-08-19 21:32:41 +00001332 }
1333}
1334
Reid Spencer1628cec2006-10-26 06:15:43 +00001335// Some constant expressions need to be casted back to the original types
1336// because their operands were casted to the expected type. This function takes
1337// care of detecting that case and printing the cast for the ConstantExpr.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001338bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001339 bool NeedsExplicitCast = false;
Reid Spencer3da59db2006-11-27 01:05:10 +00001340 const Type *Ty = CE->getOperand(0)->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001341 bool TypeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001342 switch (CE->getOpcode()) {
Dan Gohman5a11aba2008-07-18 18:43:12 +00001343 case Instruction::Add:
1344 case Instruction::Sub:
1345 case Instruction::Mul:
1346 // We need to cast integer arithmetic so that it is always performed
1347 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001348 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001349 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001350 case Instruction::UDiv: NeedsExplicitCast = true; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001351 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001352 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001353 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
Reid Spencer3da59db2006-11-27 01:05:10 +00001354 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001355 Ty = CE->getType();
1356 NeedsExplicitCast = true;
1357 TypeIsSigned = true;
1358 break;
1359 case Instruction::ZExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00001360 case Instruction::Trunc:
1361 case Instruction::FPTrunc:
1362 case Instruction::FPExt:
1363 case Instruction::UIToFP:
1364 case Instruction::SIToFP:
1365 case Instruction::FPToUI:
1366 case Instruction::FPToSI:
1367 case Instruction::PtrToInt:
1368 case Instruction::IntToPtr:
1369 case Instruction::BitCast:
1370 Ty = CE->getType();
1371 NeedsExplicitCast = true;
1372 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001373 default: break;
1374 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001375 if (NeedsExplicitCast) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001376 Out << "((";
Chris Lattner42a75512007-01-15 02:27:26 +00001377 if (Ty->isInteger() && Ty != Type::Int1Ty)
Reid Spencera54b7cb2007-01-12 07:05:14 +00001378 printSimpleType(Out, Ty, TypeIsSigned);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001379 else
Reid Spencer251f2142007-01-09 17:09:09 +00001380 printType(Out, Ty); // not integer, sign doesn't matter
Reid Spencer1628cec2006-10-26 06:15:43 +00001381 Out << ")(";
1382 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001383 return NeedsExplicitCast;
Reid Spencer1628cec2006-10-26 06:15:43 +00001384}
1385
1386// Print a constant assuming that it is the operand for a given Opcode. The
1387// opcodes that care about sign need to cast their operands to the expected
1388// type before the operation proceeds. This function does the casting.
1389void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1390
1391 // Extract the operand's type, we'll need it.
1392 const Type* OpTy = CPV->getType();
1393
1394 // Indicate whether to do the cast or not.
1395 bool shouldCast = false;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001396 bool typeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001397
1398 // Based on the Opcode for which this Constant is being written, determine
1399 // the new type to which the operand should be casted by setting the value
Reid Spencer3da59db2006-11-27 01:05:10 +00001400 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1401 // casted below.
Reid Spencer1628cec2006-10-26 06:15:43 +00001402 switch (Opcode) {
1403 default:
1404 // for most instructions, it doesn't matter
1405 break;
Dan Gohman5a11aba2008-07-18 18:43:12 +00001406 case Instruction::Add:
1407 case Instruction::Sub:
1408 case Instruction::Mul:
1409 // We need to cast integer arithmetic so that it is always performed
1410 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001411 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001412 case Instruction::UDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001413 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001414 shouldCast = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001415 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001416 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001417 case Instruction::SDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001418 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001419 shouldCast = true;
1420 typeIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001421 break;
1422 }
1423
Reid Spencer3da59db2006-11-27 01:05:10 +00001424 // Write out the casted constant if we should, otherwise just write the
Reid Spencer1628cec2006-10-26 06:15:43 +00001425 // operand.
1426 if (shouldCast) {
1427 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001428 printSimpleType(Out, OpTy, typeIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001429 Out << ")";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001430 printConstant(CPV, false);
Reid Spencer1628cec2006-10-26 06:15:43 +00001431 Out << ")";
1432 } else
Dan Gohman9f8d5712008-07-24 17:57:48 +00001433 printConstant(CPV, false);
Reid Spencer1628cec2006-10-26 06:15:43 +00001434}
1435
Bill Wendling145aad02007-02-23 22:45:08 +00001436std::string CWriter::GetValueName(const Value *Operand) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001437 // Mangle globals with the standard mangler interface for LLC compatibility.
1438 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand))
Chris Lattnerb8158ac2009-07-14 18:17:16 +00001439 return Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001440
1441 std::string Name = Operand->getName();
1442
1443 if (Name.empty()) { // Assign unique names to local temporaries.
1444 unsigned &No = AnonValueNumbers[Operand];
1445 if (No == 0)
1446 No = ++NextAnonValueNumber;
1447 Name = "tmp__" + utostr(No);
1448 }
1449
1450 std::string VarName;
1451 VarName.reserve(Name.capacity());
Bill Wendling145aad02007-02-23 22:45:08 +00001452
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001453 for (std::string::iterator I = Name.begin(), E = Name.end();
1454 I != E; ++I) {
1455 char ch = *I;
Bill Wendling145aad02007-02-23 22:45:08 +00001456
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001457 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1458 (ch >= '0' && ch <= '9') || ch == '_')) {
1459 char buffer[5];
1460 sprintf(buffer, "_%x_", ch);
1461 VarName += buffer;
1462 } else
1463 VarName += ch;
Bill Wendling145aad02007-02-23 22:45:08 +00001464 }
1465
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001466 return "llvm_cbe_" + VarName;
Bill Wendling145aad02007-02-23 22:45:08 +00001467}
1468
Chris Lattnere56d9462008-05-31 09:23:55 +00001469/// writeInstComputationInline - Emit the computation for the specified
1470/// instruction inline, with no destination provided.
1471void CWriter::writeInstComputationInline(Instruction &I) {
Dale Johannesen06398942009-06-18 01:07:23 +00001472 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1473 // Validate this.
1474 const Type *Ty = I.getType();
1475 if (Ty->isInteger() && (Ty!=Type::Int1Ty && Ty!=Type::Int8Ty &&
1476 Ty!=Type::Int16Ty && Ty!=Type::Int32Ty && Ty!=Type::Int64Ty)) {
Torok Edwindac237e2009-07-08 20:53:28 +00001477 llvm_report_error("The C backend does not currently support integer "
1478 "types of widths other than 1, 8, 16, 32, 64.\n"
1479 "This is being tracked as PR 4158.");
Dale Johannesen06398942009-06-18 01:07:23 +00001480 }
1481
Chris Lattnere56d9462008-05-31 09:23:55 +00001482 // If this is a non-trivial bool computation, make sure to truncate down to
1483 // a 1 bit value. This is important because we want "add i1 x, y" to return
1484 // "0" when x and y are true, not "2" for example.
1485 bool NeedBoolTrunc = false;
1486 if (I.getType() == Type::Int1Ty && !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
1487 NeedBoolTrunc = true;
1488
1489 if (NeedBoolTrunc)
1490 Out << "((";
1491
1492 visit(I);
1493
1494 if (NeedBoolTrunc)
1495 Out << ")&1)";
1496}
1497
1498
Dan Gohman9f8d5712008-07-24 17:57:48 +00001499void CWriter::writeOperandInternal(Value *Operand, bool Static) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001500 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnere56d9462008-05-31 09:23:55 +00001501 // Should we inline this instruction to build a tree?
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001502 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001503 Out << '(';
Chris Lattnere56d9462008-05-31 09:23:55 +00001504 writeInstComputationInline(*I);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001505 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001506 return;
1507 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001508
Reid Spencer518310c2004-07-18 00:44:37 +00001509 Constant* CPV = dyn_cast<Constant>(Operand);
Bill Wendling145aad02007-02-23 22:45:08 +00001510
1511 if (CPV && !isa<GlobalValue>(CPV))
Dan Gohman9f8d5712008-07-24 17:57:48 +00001512 printConstant(CPV, Static);
Bill Wendling145aad02007-02-23 22:45:08 +00001513 else
1514 Out << GetValueName(Operand);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001515}
1516
Dan Gohman9f8d5712008-07-24 17:57:48 +00001517void CWriter::writeOperand(Value *Operand, bool Static) {
Chris Lattnere05252b42008-03-02 08:07:24 +00001518 bool isAddressImplicit = isAddressExposed(Operand);
1519 if (isAddressImplicit)
Reid Spencer3da59db2006-11-27 01:05:10 +00001520 Out << "(&"; // Global variables are referenced as their addresses by llvm
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001521
Dan Gohman9f8d5712008-07-24 17:57:48 +00001522 writeOperandInternal(Operand, Static);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001523
Chris Lattnere05252b42008-03-02 08:07:24 +00001524 if (isAddressImplicit)
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001525 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001526}
1527
Reid Spencer1628cec2006-10-26 06:15:43 +00001528// Some instructions need to have their result value casted back to the
1529// original types because their operands were casted to the expected type.
1530// This function takes care of detecting that case and printing the cast
1531// for the Instruction.
1532bool CWriter::writeInstructionCast(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001533 const Type *Ty = I.getOperand(0)->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00001534 switch (I.getOpcode()) {
Dan Gohman5a11aba2008-07-18 18:43:12 +00001535 case Instruction::Add:
1536 case Instruction::Sub:
1537 case Instruction::Mul:
1538 // We need to cast integer arithmetic so that it is always performed
1539 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001540 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001541 case Instruction::URem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001542 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001543 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001544 printSimpleType(Out, Ty, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001545 Out << ")(";
1546 return true;
Reid Spencer3822ff52006-11-08 06:47:33 +00001547 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001548 case Instruction::SRem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001549 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001550 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001551 printSimpleType(Out, Ty, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001552 Out << ")(";
1553 return true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001554 default: break;
1555 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001556 return false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001557}
1558
1559// Write the operand with a cast to another type based on the Opcode being used.
1560// This will be used in cases where an instruction has specific type
1561// requirements (usually signedness) for its operands.
1562void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1563
1564 // Extract the operand's type, we'll need it.
1565 const Type* OpTy = Operand->getType();
1566
1567 // Indicate whether to do the cast or not.
1568 bool shouldCast = false;
1569
Reid Spencere4d87aa2006-12-23 06:05:41 +00001570 // Indicate whether the cast should be to a signed type or not.
1571 bool castIsSigned = false;
1572
Reid Spencer1628cec2006-10-26 06:15:43 +00001573 // Based on the Opcode for which this Operand is being written, determine
1574 // the new type to which the operand should be casted by setting the value
1575 // of OpTy. If we change OpTy, also set shouldCast to true.
1576 switch (Opcode) {
1577 default:
1578 // for most instructions, it doesn't matter
1579 break;
Dan Gohman5a11aba2008-07-18 18:43:12 +00001580 case Instruction::Add:
1581 case Instruction::Sub:
1582 case Instruction::Mul:
1583 // We need to cast integer arithmetic so that it is always performed
1584 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001585 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001586 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001587 case Instruction::URem: // Cast to unsigned first
1588 shouldCast = true;
1589 castIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001590 break;
Chris Lattner96b207c2007-09-22 20:16:48 +00001591 case Instruction::GetElementPtr:
Reid Spencer3822ff52006-11-08 06:47:33 +00001592 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001593 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001594 case Instruction::SRem: // Cast to signed first
1595 shouldCast = true;
1596 castIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001597 break;
1598 }
1599
1600 // Write out the casted operand if we should, otherwise just write the
1601 // operand.
1602 if (shouldCast) {
1603 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001604 printSimpleType(Out, OpTy, castIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001605 Out << ")";
Chris Lattner72623362007-05-03 02:57:13 +00001606 writeOperand(Operand);
Reid Spencer1628cec2006-10-26 06:15:43 +00001607 Out << ")";
1608 } else
1609 writeOperand(Operand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001610}
Reid Spencer1628cec2006-10-26 06:15:43 +00001611
Reid Spencere4d87aa2006-12-23 06:05:41 +00001612// Write the operand with a cast to another type based on the icmp predicate
1613// being used.
Chris Lattner5bda9e42007-09-15 06:51:03 +00001614void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1615 // This has to do a cast to ensure the operand has the right signedness.
1616 // Also, if the operand is a pointer, we make sure to cast to an integer when
1617 // doing the comparison both for signedness and so that the C compiler doesn't
1618 // optimize things like "p < NULL" to false (p may contain an integer value
1619 // f.e.).
1620 bool shouldCast = Cmp.isRelational();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001621
1622 // Write out the casted operand if we should, otherwise just write the
1623 // operand.
Chris Lattner5bda9e42007-09-15 06:51:03 +00001624 if (!shouldCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001625 writeOperand(Operand);
Chris Lattner5bda9e42007-09-15 06:51:03 +00001626 return;
1627 }
1628
1629 // Should this be a signed comparison? If so, convert to signed.
1630 bool castIsSigned = Cmp.isSignedPredicate();
1631
1632 // If the operand was a pointer, convert to a large integer type.
1633 const Type* OpTy = Operand->getType();
1634 if (isa<PointerType>(OpTy))
1635 OpTy = TD->getIntPtrType();
1636
1637 Out << "((";
1638 printSimpleType(Out, OpTy, castIsSigned);
1639 Out << ")";
1640 writeOperand(Operand);
1641 Out << ")";
Reid Spencer1628cec2006-10-26 06:15:43 +00001642}
1643
Chris Lattner41488192003-06-28 17:15:12 +00001644// generateCompilerSpecificCode - This is where we add conditional compilation
1645// directives to cater to specific compilers as need be.
1646//
David Greene71847812009-07-14 20:18:05 +00001647static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
Dan Gohman271515a2008-04-02 23:52:49 +00001648 const TargetData *TD) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001649 // Alloca is hard to get, and we don't want to include stdlib.h here.
Chris Lattner41488192003-06-28 17:15:12 +00001650 Out << "/* get a declaration for alloca */\n"
Chris Lattnerd9477602006-06-02 18:54:01 +00001651 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
Anton Korobeynikov57fc00d2007-04-17 09:20:00 +00001652 << "#define alloca(x) __builtin_alloca((x))\n"
1653 << "#define _alloca(x) __builtin_alloca((x))\n"
Reid Spencera8411a62005-01-23 04:32:47 +00001654 << "#elif defined(__APPLE__)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001655 << "extern void *__builtin_alloca(unsigned long);\n"
1656 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001657 << "#define longjmp _longjmp\n"
1658 << "#define setjmp _setjmp\n"
Brian Gaekece630052004-12-10 05:44:45 +00001659 << "#elif defined(__sun__)\n"
1660 << "#if defined(__sparcv9)\n"
1661 << "extern void *__builtin_alloca(unsigned long);\n"
1662 << "#else\n"
1663 << "extern void *__builtin_alloca(unsigned int);\n"
1664 << "#endif\n"
1665 << "#define alloca(x) __builtin_alloca(x)\n"
Matthijs Kooijmanf5122812008-06-26 10:36:58 +00001666 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)\n"
Chris Lattner60e66742004-10-06 04:21:52 +00001667 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohenab478952007-03-28 23:08:37 +00001668 << "#elif defined(_MSC_VER)\n"
Jeff Cohene2cd2a02007-03-29 17:42:21 +00001669 << "#define inline _inline\n"
Jeff Cohenab478952007-03-28 23:08:37 +00001670 << "#define alloca(x) _alloca(x)\n"
1671 << "#else\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001672 << "#include <alloca.h>\n"
1673 << "#endif\n\n";
Chris Lattner41488192003-06-28 17:15:12 +00001674
1675 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1676 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner9bda5f52003-06-28 17:53:05 +00001677 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattner41488192003-06-28 17:15:12 +00001678 << "#define __attribute__(X)\n"
Brian Gaeke27f7a712003-12-11 00:24:36 +00001679 << "#endif\n\n";
1680
Brian Gaeke27f7a712003-12-11 00:24:36 +00001681 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1682 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1683 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1684 << "#elif defined(__GNUC__)\n"
1685 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1686 << "#else\n"
1687 << "#define __EXTERNAL_WEAK__\n"
1688 << "#endif\n\n";
Brian Gaeke27f7a712003-12-11 00:24:36 +00001689
1690 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1691 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1692 << "#define __ATTRIBUTE_WEAK__\n"
1693 << "#elif defined(__GNUC__)\n"
1694 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1695 << "#else\n"
1696 << "#define __ATTRIBUTE_WEAK__\n"
1697 << "#endif\n\n";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001698
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001699 // Add hidden visibility support. FIXME: APPLE_CC?
1700 Out << "#if defined(__GNUC__)\n"
1701 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1702 << "#endif\n\n";
1703
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001704 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1705 // From the GCC documentation:
Misha Brukmand6a29a52005-04-20 16:05:03 +00001706 //
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001707 // double __builtin_nan (const char *str)
1708 //
1709 // This is an implementation of the ISO C99 function nan.
1710 //
1711 // Since ISO C99 defines this function in terms of strtod, which we do
1712 // not implement, a description of the parsing is in order. The string is
1713 // parsed as by strtol; that is, the base is recognized by leading 0 or
1714 // 0x prefixes. The number parsed is placed in the significand such that
1715 // the least significant bit of the number is at the least significant
1716 // bit of the significand. The number is truncated to fit the significand
1717 // field provided. The significand is forced to be a quiet NaN.
1718 //
1719 // This function, if given a string literal, is evaluated early enough
1720 // that it is considered a compile-time constant.
1721 //
1722 // float __builtin_nanf (const char *str)
1723 //
1724 // Similar to __builtin_nan, except the return type is float.
1725 //
1726 // double __builtin_inf (void)
1727 //
1728 // Similar to __builtin_huge_val, except a warning is generated if the
1729 // target floating-point format does not support infinities. This
1730 // function is suitable for implementing the ISO C99 macro INFINITY.
1731 //
1732 // float __builtin_inff (void)
1733 //
1734 // Similar to __builtin_inf, except the return type is float.
1735 Out << "#ifdef __GNUC__\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001736 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1737 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1738 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1739 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1740 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1741 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
Chris Lattnerf9a05322006-02-13 22:22:42 +00001742 << "#define LLVM_PREFETCH(addr,rw,locality) "
1743 "__builtin_prefetch(addr,rw,locality)\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001744 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1745 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001746 << "#define LLVM_ASM __asm__\n"
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001747 << "#else\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001748 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1749 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1750 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1751 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1752 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1753 << "#define LLVM_INFF 0.0F /* Float */\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001754 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001755 << "#define __ATTRIBUTE_CTOR__\n"
1756 << "#define __ATTRIBUTE_DTOR__\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001757 << "#define LLVM_ASM(X)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001758 << "#endif\n\n";
Chris Lattner40c1b662007-05-13 22:19:27 +00001759
1760 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1761 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1762 << "#define __builtin_stack_restore(X) /* noop */\n"
1763 << "#endif\n\n";
Chris Lattner50a8a172005-05-06 06:58:42 +00001764
Dan Gohman271515a2008-04-02 23:52:49 +00001765 // Output typedefs for 128-bit integers. If these are needed with a
1766 // 32-bit target or with a C compiler that doesn't support mode(TI),
1767 // more drastic measures will be needed.
Chris Lattner9e4ff942008-06-16 04:25:29 +00001768 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1769 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1770 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1771 << "#endif\n\n";
Dan Gohmand7614802008-04-02 19:40:14 +00001772
Chris Lattner50a8a172005-05-06 06:58:42 +00001773 // Output target-specific code that should be inserted into main.
1774 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001775}
1776
Chris Lattner9a571ba2006-03-07 22:58:23 +00001777/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1778/// the StaticTors set.
1779static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1780 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1781 if (!InitList) return;
1782
1783 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1784 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1785 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1786
1787 if (CS->getOperand(1)->isNullValue())
1788 return; // Found a null terminator, exit printing.
1789 Constant *FP = CS->getOperand(1);
1790 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +00001791 if (CE->isCast())
Chris Lattner9a571ba2006-03-07 22:58:23 +00001792 FP = CE->getOperand(0);
1793 if (Function *F = dyn_cast<Function>(FP))
1794 StaticTors.insert(F);
1795 }
1796}
1797
1798enum SpecialGlobalClass {
1799 NotSpecial = 0,
1800 GlobalCtors, GlobalDtors,
1801 NotPrinted
1802};
1803
1804/// getGlobalVariableClass - If this is a global that is specially recognized
1805/// by LLVM, return a code that indicates how we should handle it.
1806static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1807 // If this is a global ctors/dtors list, handle it now.
1808 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1809 if (GV->getName() == "llvm.global_ctors")
1810 return GlobalCtors;
1811 else if (GV->getName() == "llvm.global_dtors")
1812 return GlobalDtors;
1813 }
1814
1815 // Otherwise, it it is other metadata, don't print it. This catches things
1816 // like debug information.
1817 if (GV->getSection() == "llvm.metadata")
1818 return NotPrinted;
1819
1820 return NotSpecial;
1821}
1822
1823
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001824bool CWriter::doInitialization(Module &M) {
1825 // Initialize
1826 TheModule = &M;
Chris Lattnerc2421432004-05-09 04:30:20 +00001827
Reid Spencer519e2392007-01-29 17:51:02 +00001828 TD = new TargetData(&M);
1829 IL = new IntrinsicLowering(*TD);
1830 IL->AddPrototypes(M);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001831
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001832 // Ensure that all structure types have names...
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001833 Mang = new Mangler(M);
Chris Lattnerba9c6432005-11-10 21:39:29 +00001834 Mang->markCharUnacceptable('.');
Chris Lattnerc59c1182003-11-16 22:06:14 +00001835
Chris Lattner9a571ba2006-03-07 22:58:23 +00001836 // Keep track of which functions are static ctors/dtors so they can have
1837 // an attribute added to their prototypes.
1838 std::set<Function*> StaticCtors, StaticDtors;
1839 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1840 I != E; ++I) {
1841 switch (getGlobalVariableClass(I)) {
1842 default: break;
1843 case GlobalCtors:
1844 FindStaticTors(I, StaticCtors);
1845 break;
1846 case GlobalDtors:
1847 FindStaticTors(I, StaticDtors);
1848 break;
1849 }
1850 }
1851
Chris Lattner16c7bb22002-05-09 02:28:59 +00001852 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001853 Out << "/* Provide Declarations */\n";
Chris Lattnerc59c1182003-11-16 22:06:14 +00001854 Out << "#include <stdarg.h>\n"; // Varargs support
1855 Out << "#include <setjmp.h>\n"; // Unwind support
Dan Gohman271515a2008-04-02 23:52:49 +00001856 generateCompilerSpecificCode(Out, TD);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001857
Chris Lattnercf135cb2003-06-02 03:10:53 +00001858 // Provide a definition for `bool' if not compiling with a C++ compiler.
1859 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +00001860 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001861
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001862 << "\n\n/* Support for floating point constants */\n"
1863 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +00001864 << "typedef unsigned int ConstantFloatTy;\n"
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001865 << "typedef struct { unsigned long long f1; unsigned short f2; "
1866 "unsigned short pad[3]; } ConstantFP80Ty;\n"
Dale Johannesen6e644732007-10-15 01:05:37 +00001867 // This is used for both kinds of 128-bit long double; meaning differs.
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001868 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1869 " ConstantFP128Ty;\n"
Chris Lattnera4d4a852002-08-19 21:48:40 +00001870 << "\n\n/* Global Declarations */\n";
1871
1872 // First output all the declarations for the program, because C requires
1873 // Functions & globals to be declared before they are used.
1874 //
Chris Lattner16c7bb22002-05-09 02:28:59 +00001875
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001876 // Loop over the symbol table, emitting all named constants...
Reid Spencer78d033e2007-01-06 07:24:44 +00001877 printModuleTypes(M.getTypeSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001878
Chris Lattnera4d4a852002-08-19 21:48:40 +00001879 // Global variable declarations...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001880 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001881 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001882 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1883 I != E; ++I) {
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001884
Dale Johannesenaafce772008-05-14 20:12:51 +00001885 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1886 I->hasCommonLinkage())
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001887 Out << "extern ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001888 else if (I->hasDLLImportLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001889 Out << "__declspec(dllimport) ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001890 else
1891 continue; // Internal Global
1892
1893 // Thread Local Storage
1894 if (I->isThreadLocal())
1895 Out << "__thread ";
1896
1897 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1898
1899 if (I->hasExternalWeakLinkage())
1900 Out << " __EXTERNAL_WEAK__";
1901 Out << ";\n";
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001902 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001903 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001904
Chris Lattnera4d4a852002-08-19 21:48:40 +00001905 // Function declarations
Chris Lattner9a571ba2006-03-07 22:58:23 +00001906 Out << "\n/* Function Declarations */\n";
Chris Lattner57da2522005-08-23 20:22:50 +00001907 Out << "double fmod(double, double);\n"; // Support for FP rem
1908 Out << "float fmodf(float, float);\n";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001909 Out << "long double fmodl(long double, long double);\n";
Evan Cheng3e3aa862008-06-07 07:50:29 +00001910
Chris Lattner9a571ba2006-03-07 22:58:23 +00001911 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1912 // Don't print declarations for intrinsic functions.
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001913 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
Reid Spencer2cb46e12006-10-22 09:58:21 +00001914 I->getName() != "longjmp" && I->getName() != "_setjmp") {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001915 if (I->hasExternalWeakLinkage())
1916 Out << "extern ";
Chris Lattner9a571ba2006-03-07 22:58:23 +00001917 printFunctionSignature(I, true);
Evan Cheng3e3aa862008-06-07 07:50:29 +00001918 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
Chris Lattner9a571ba2006-03-07 22:58:23 +00001919 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001920 if (I->hasExternalWeakLinkage())
1921 Out << " __EXTERNAL_WEAK__";
Chris Lattner9a571ba2006-03-07 22:58:23 +00001922 if (StaticCtors.count(I))
1923 Out << " __ATTRIBUTE_CTOR__";
1924 if (StaticDtors.count(I))
1925 Out << " __ATTRIBUTE_DTOR__";
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001926 if (I->hasHiddenVisibility())
1927 Out << " __HIDDEN__";
Evan Cheng3e3aa862008-06-07 07:50:29 +00001928
1929 if (I->hasName() && I->getName()[0] == 1)
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001930 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
Evan Cheng3e3aa862008-06-07 07:50:29 +00001931
Chris Lattner9a571ba2006-03-07 22:58:23 +00001932 Out << ";\n";
Chris Lattner4cda8352002-08-20 16:55:48 +00001933 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001934 }
1935
Joel Stanley54f60322003-06-25 04:52:09 +00001936 // Output the global variable declarations
Chris Lattnere4d5c442005-03-15 04:54:21 +00001937 if (!M.global_empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +00001938 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001939 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1940 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +00001941 if (!I->isDeclaration()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001942 // Ignore special globals, such as debug info.
1943 if (getGlobalVariableClass(I))
1944 continue;
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001945
Rafael Espindolabb46f522009-01-15 20:18:42 +00001946 if (I->hasLocalLinkage())
Chris Lattnercc16a8e2004-12-03 17:19:10 +00001947 Out << "static ";
1948 else
1949 Out << "extern ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001950
1951 // Thread Local Storage
1952 if (I->isThreadLocal())
1953 Out << "__thread ";
1954
Reid Spencer251f2142007-01-09 17:09:09 +00001955 printType(Out, I->getType()->getElementType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00001956 GetValueName(I));
Chris Lattner2580d4f2003-11-03 17:32:38 +00001957
1958 if (I->hasLinkOnceLinkage())
1959 Out << " __attribute__((common))";
Dale Johannesenaafce772008-05-14 20:12:51 +00001960 else if (I->hasCommonLinkage()) // FIXME is this right?
1961 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner2580d4f2003-11-03 17:32:38 +00001962 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001963 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001964 else if (I->hasExternalWeakLinkage())
1965 Out << " __EXTERNAL_WEAK__";
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001966 if (I->hasHiddenVisibility())
1967 Out << " __HIDDEN__";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001968 Out << ";\n";
1969 }
1970 }
1971
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001972 // Output the global variable definitions and contents...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001973 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001974 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Evan Cheng3e3aa862008-06-07 07:50:29 +00001975 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
Chris Lattnerf9a05322006-02-13 22:22:42 +00001976 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +00001977 if (!I->isDeclaration()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001978 // Ignore special globals, such as debug info.
1979 if (getGlobalVariableClass(I))
1980 continue;
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001981
Rafael Espindolabb46f522009-01-15 20:18:42 +00001982 if (I->hasLocalLinkage())
Chris Lattnere8e035b2002-10-16 20:08:47 +00001983 Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001984 else if (I->hasDLLImportLinkage())
1985 Out << "__declspec(dllimport) ";
1986 else if (I->hasDLLExportLinkage())
1987 Out << "__declspec(dllexport) ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001988
1989 // Thread Local Storage
1990 if (I->isThreadLocal())
1991 Out << "__thread ";
1992
Reid Spencer251f2142007-01-09 17:09:09 +00001993 printType(Out, I->getType()->getElementType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00001994 GetValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +00001995 if (I->hasLinkOnceLinkage())
1996 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +00001997 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001998 Out << " __ATTRIBUTE_WEAK__";
Dale Johannesenaafce772008-05-14 20:12:51 +00001999 else if (I->hasCommonLinkage())
2000 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner5ea326a2003-11-03 17:35:00 +00002001
Anton Korobeynikov7f705592007-01-12 19:20:47 +00002002 if (I->hasHiddenVisibility())
2003 Out << " __HIDDEN__";
2004
Chris Lattner5ea326a2003-11-03 17:35:00 +00002005 // If the initializer is not null, emit the initializer. If it is null,
2006 // we try to avoid emitting large amounts of zeros. The problem with
2007 // this, however, occurs when the variable has weak linkage. In this
2008 // case, the assembler will complain about the variable being both weak
2009 // and common, so we disable this optimization.
Dale Johannesenaafce772008-05-14 20:12:51 +00002010 // FIXME common linkage should avoid this problem.
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002011 if (!I->getInitializer()->isNullValue()) {
Chris Lattner940b08d2003-06-06 07:10:24 +00002012 Out << " = " ;
Dan Gohman9f8d5712008-07-24 17:57:48 +00002013 writeOperand(I->getInitializer(), true);
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002014 } else if (I->hasWeakLinkage()) {
2015 // We have to specify an initializer, but it doesn't have to be
2016 // complete. If the value is an aggregate, print out { 0 }, and let
2017 // the compiler figure out the rest of the zeros.
2018 Out << " = " ;
2019 if (isa<StructType>(I->getInitializer()->getType()) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00002020 isa<VectorType>(I->getInitializer()->getType())) {
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002021 Out << "{ 0 }";
Dan Gohman193c2352008-06-02 21:30:49 +00002022 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
2023 // As with structs and vectors, but with an extra set of braces
2024 // because arrays are wrapped in structs.
2025 Out << "{ { 0 } }";
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002026 } else {
2027 // Just print it out normally.
Dan Gohman9f8d5712008-07-24 17:57:48 +00002028 writeOperand(I->getInitializer(), true);
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002029 }
Chris Lattner940b08d2003-06-06 07:10:24 +00002030 }
Chris Lattnere8e035b2002-10-16 20:08:47 +00002031 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00002032 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00002033 }
2034
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002035 if (!M.empty())
Chris Lattnera4d4a852002-08-19 21:48:40 +00002036 Out << "\n\n/* Function Bodies */\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002037
2038 // Emit some helper functions for dealing with FCMP instruction's
2039 // predicates
2040 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2041 Out << "return X == X && Y == Y; }\n";
2042 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2043 Out << "return X != X || Y != Y; }\n";
2044 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002045 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002046 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002047 Out << "return X != Y; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002048 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002049 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002050 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002051 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002052 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002053 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002054 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002055 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002056 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002057 Out << "return X == Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002058 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002059 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002060 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002061 Out << "return X < Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002062 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002063 Out << "return X > Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002064 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002065 Out << "return X <= Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002066 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002067 Out << "return X >= Y ; }\n";
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002068 return false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002069}
2070
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002071
Chris Lattner9860e772003-10-12 04:36:29 +00002072/// Output all floating point constants that cannot be printed accurately...
Chris Lattner68758072004-05-09 06:20:51 +00002073void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner9860e772003-10-12 04:36:29 +00002074 // Scan the module for floating point constants. If any FP constant is used
2075 // in the function, we want to redirect it here so that we do not depend on
2076 // the precision of the printed form, unless the printed form preserves
2077 // precision.
2078 //
Chris Lattner68758072004-05-09 06:20:51 +00002079 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2080 I != E; ++I)
Chris Lattneraecc22a2008-10-22 04:53:16 +00002081 printFloatingPointConstants(*I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002082
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002083 Out << '\n';
Chris Lattner68758072004-05-09 06:20:51 +00002084}
Chris Lattner9860e772003-10-12 04:36:29 +00002085
Chris Lattneraecc22a2008-10-22 04:53:16 +00002086void CWriter::printFloatingPointConstants(const Constant *C) {
2087 // If this is a constant expression, recursively check for constant fp values.
2088 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2089 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2090 printFloatingPointConstants(CE->getOperand(i));
2091 return;
2092 }
2093
2094 // Otherwise, check for a FP constant that we need to print.
2095 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2096 if (FPC == 0 ||
2097 // Do not put in FPConstantMap if safe.
2098 isFPCSafeToPrint(FPC) ||
2099 // Already printed this constant?
2100 FPConstantMap.count(FPC))
2101 return;
2102
2103 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2104
2105 if (FPC->getType() == Type::DoubleTy) {
2106 double Val = FPC->getValueAPF().convertToDouble();
2107 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2108 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2109 << " = 0x" << utohexstr(i)
2110 << "ULL; /* " << Val << " */\n";
2111 } else if (FPC->getType() == Type::FloatTy) {
2112 float Val = FPC->getValueAPF().convertToFloat();
2113 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2114 getZExtValue();
2115 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2116 << " = 0x" << utohexstr(i)
2117 << "U; /* " << Val << " */\n";
2118 } else if (FPC->getType() == Type::X86_FP80Ty) {
2119 // api needed to prevent premature destruction
2120 APInt api = FPC->getValueAPF().bitcastToAPInt();
2121 const uint64_t *p = api.getRawData();
2122 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002123 << " = { 0x" << utohexstr(p[0])
2124 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
Chris Lattneraecc22a2008-10-22 04:53:16 +00002125 << "}; /* Long double constant */\n";
2126 } else if (FPC->getType() == Type::PPC_FP128Ty) {
2127 APInt api = FPC->getValueAPF().bitcastToAPInt();
2128 const uint64_t *p = api.getRawData();
2129 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2130 << " = { 0x"
2131 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2132 << "}; /* Long double constant */\n";
2133
2134 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002135 llvm_unreachable("Unknown float type!");
Chris Lattneraecc22a2008-10-22 04:53:16 +00002136 }
2137}
2138
2139
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002140
Chris Lattner2db41cd2002-09-20 15:12:13 +00002141/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchinob78e8382006-01-20 20:43:57 +00002142/// type name is found, emit its declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +00002143///
Reid Spencer78d033e2007-01-06 07:24:44 +00002144void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
Reid Spencer555a0b12006-12-11 20:39:15 +00002145 Out << "/* Helper union for bitcasts */\n";
2146 Out << "typedef union {\n";
Reid Spencer47857812006-12-31 05:55:36 +00002147 Out << " unsigned int Int32;\n";
2148 Out << " unsigned long long Int64;\n";
Reid Spencer22b36fb2006-12-12 00:11:08 +00002149 Out << " float Float;\n";
2150 Out << " double Double;\n";
Reid Spencer555a0b12006-12-11 20:39:15 +00002151 Out << "} llvmBitCastUnion;\n";
2152
Chris Lattnerb15fde22005-03-06 02:28:23 +00002153 // We are only interested in the type plane of the symbol table.
Reid Spencer78d033e2007-01-06 07:24:44 +00002154 TypeSymbolTable::const_iterator I = TST.begin();
2155 TypeSymbolTable::const_iterator End = TST.end();
Chris Lattnerb15fde22005-03-06 02:28:23 +00002156
2157 // If there are no type names, exit early.
2158 if (I == End) return;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002159
Chris Lattner58d04d42002-09-20 15:18:30 +00002160 // Print out forward declarations for structure types before anything else!
2161 Out << "/* Structure forward decls */\n";
Chris Lattnera80cc932007-01-16 18:02:45 +00002162 for (; I != End; ++I) {
2163 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
2164 Out << Name << ";\n";
2165 TypeNames.insert(std::make_pair(I->second, Name));
2166 }
Chris Lattner58d04d42002-09-20 15:18:30 +00002167
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002168 Out << '\n';
Chris Lattner58d04d42002-09-20 15:18:30 +00002169
Chris Lattner19e8b0c2007-01-16 07:22:23 +00002170 // Now we can print out typedefs. Above, we guaranteed that this can only be
Chris Lattnera80cc932007-01-16 18:02:45 +00002171 // for struct or opaque types.
Chris Lattner58d04d42002-09-20 15:18:30 +00002172 Out << "/* Typedefs */\n";
Reid Spencer78d033e2007-01-06 07:24:44 +00002173 for (I = TST.begin(); I != End; ++I) {
Chris Lattner36c975c2005-11-10 18:53:25 +00002174 std::string Name = "l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00002175 Out << "typedef ";
Chris Lattnera80cc932007-01-16 18:02:45 +00002176 printType(Out, I->second, false, Name);
Chris Lattner68758072004-05-09 06:20:51 +00002177 Out << ";\n";
2178 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002179
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002180 Out << '\n';
Chris Lattner3ef6dc72002-05-09 14:40:11 +00002181
Chris Lattner2c601a72002-09-20 15:05:40 +00002182 // Keep track of which structures have been printed so far...
Dan Gohman193c2352008-06-02 21:30:49 +00002183 std::set<const Type *> StructPrinted;
Chris Lattner2c601a72002-09-20 15:05:40 +00002184
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002185 // Loop over all structures then push them into the stack so they are
2186 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +00002187 //
Chris Lattner58d04d42002-09-20 15:18:30 +00002188 Out << "/* Structure contents */\n";
Reid Spencer78d033e2007-01-06 07:24:44 +00002189 for (I = TST.begin(); I != End; ++I)
Dan Gohman193c2352008-06-02 21:30:49 +00002190 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
Chris Lattnerfa395ec2003-11-02 01:29:27 +00002191 // Only print out used types!
Dan Gohman193c2352008-06-02 21:30:49 +00002192 printContainedStructs(I->second, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002193}
2194
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002195// Push the struct onto the stack and recursively push all structs
2196// this one depends on.
Robert Bocchinob78e8382006-01-20 20:43:57 +00002197//
Reid Spencerac9dcb92007-02-15 03:39:18 +00002198// TODO: Make this work properly with vector types
Robert Bocchinob78e8382006-01-20 20:43:57 +00002199//
Chris Lattner2c601a72002-09-20 15:05:40 +00002200void CWriter::printContainedStructs(const Type *Ty,
Dan Gohman193c2352008-06-02 21:30:49 +00002201 std::set<const Type*> &StructPrinted) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002202 // Don't walk through pointers.
Chris Lattner42a75512007-01-15 02:27:26 +00002203 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
Chris Lattner14d9b202006-01-20 18:57:03 +00002204
2205 // Print all contained types first.
2206 for (Type::subtype_iterator I = Ty->subtype_begin(),
2207 E = Ty->subtype_end(); I != E; ++I)
2208 printContainedStructs(*I, StructPrinted);
2209
Dan Gohman193c2352008-06-02 21:30:49 +00002210 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002211 // Check to see if we have already printed this struct.
Dan Gohman193c2352008-06-02 21:30:49 +00002212 if (StructPrinted.insert(Ty).second) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002213 // Print structure type out.
Dan Gohman193c2352008-06-02 21:30:49 +00002214 std::string Name = TypeNames[Ty];
2215 printType(Out, Ty, false, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00002216 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002217 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002218 }
2219}
2220
Chris Lattner4cda8352002-08-20 16:55:48 +00002221void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002222 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002223 bool isStructReturn = F->hasStructRetAttr();
Chris Lattner0c54d892006-05-23 23:39:48 +00002224
Rafael Espindolabb46f522009-01-15 20:18:42 +00002225 if (F->hasLocalLinkage()) Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002226 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2227 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002228 switch (F->getCallingConv()) {
2229 case CallingConv::X86_StdCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002230 Out << "__attribute__((stdcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002231 break;
2232 case CallingConv::X86_FastCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002233 Out << "__attribute__((fastcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002234 break;
2235 }
2236
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002237 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00002238 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Devang Patel05988662008-09-25 21:00:45 +00002239 const AttrListPtr &PAL = F->getAttributes();
Misha Brukmand6a29a52005-04-20 16:05:03 +00002240
2241 std::stringstream FunctionInnards;
2242
Nick Hildenbrandt98502372002-11-18 20:55:50 +00002243 // Print out the name...
Bill Wendling145aad02007-02-23 22:45:08 +00002244 FunctionInnards << GetValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00002245
Chris Lattner0c54d892006-05-23 23:39:48 +00002246 bool PrintedArg = false;
Reid Spencer5cbf9852007-01-30 20:08:39 +00002247 if (!F->isDeclaration()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00002248 if (!F->arg_empty()) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002249 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
Evan Cheng681d2b82008-01-11 03:07:46 +00002250 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +00002251
2252 // If this is a struct-return function, don't print the hidden
2253 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002254 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002255 assert(I != E && "Invalid struct return function!");
2256 ++I;
Evan Cheng681d2b82008-01-11 03:07:46 +00002257 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002258 }
2259
Chris Lattneredd8ce12003-05-03 03:14:35 +00002260 std::string ArgName;
Chris Lattner0c54d892006-05-23 23:39:48 +00002261 for (; I != E; ++I) {
2262 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00002263 if (I->hasName() || !Prototype)
Bill Wendling145aad02007-02-23 22:45:08 +00002264 ArgName = GetValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002265 else
Chris Lattner4cda8352002-08-20 16:55:48 +00002266 ArgName = "";
Evan Cheng681d2b82008-01-11 03:07:46 +00002267 const Type *ArgTy = I->getType();
Devang Patel05988662008-09-25 21:00:45 +00002268 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng588c6f82008-01-11 09:12:49 +00002269 ArgTy = cast<PointerType>(ArgTy)->getElementType();
Chris Lattnere05252b42008-03-02 08:07:24 +00002270 ByValParams.insert(I);
Evan Cheng588c6f82008-01-11 09:12:49 +00002271 }
Evan Cheng681d2b82008-01-11 03:07:46 +00002272 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002273 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002274 ArgName);
Chris Lattner0c54d892006-05-23 23:39:48 +00002275 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002276 ++Idx;
Chris Lattnerdeed7a52002-05-09 15:18:52 +00002277 }
2278 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002279 } else {
Chris Lattner0c54d892006-05-23 23:39:48 +00002280 // Loop over the arguments, printing them.
2281 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
Evan Cheng3d794782008-01-11 23:10:11 +00002282 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +00002283
2284 // If this is a struct-return function, don't print the hidden
2285 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002286 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002287 assert(I != E && "Invalid struct return function!");
2288 ++I;
Evan Cheng3d794782008-01-11 23:10:11 +00002289 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002290 }
2291
2292 for (; I != E; ++I) {
2293 if (PrintedArg) FunctionInnards << ", ";
Evan Cheng3d794782008-01-11 23:10:11 +00002294 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +00002295 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng3d794782008-01-11 23:10:11 +00002296 assert(isa<PointerType>(ArgTy));
2297 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2298 }
2299 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002300 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
Chris Lattner0c54d892006-05-23 23:39:48 +00002301 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002302 ++Idx;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002303 }
2304 }
2305
Chris Lattner1f8c4a12002-09-20 22:32:30 +00002306 // Finish printing arguments... if this is a vararg function, print the ...,
2307 // unless there are no known types, in which case, we just emit ().
2308 //
Chris Lattner0c54d892006-05-23 23:39:48 +00002309 if (FT->isVarArg() && PrintedArg) {
2310 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00002311 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattner0c54d892006-05-23 23:39:48 +00002312 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00002313 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002314 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002315 FunctionInnards << ')';
Chris Lattner0c54d892006-05-23 23:39:48 +00002316
2317 // Get the return tpe for the function.
2318 const Type *RetTy;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002319 if (!isStructReturn)
Chris Lattner0c54d892006-05-23 23:39:48 +00002320 RetTy = F->getReturnType();
2321 else {
2322 // If this is a struct-return function, print the struct-return type.
2323 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2324 }
2325
2326 // Print out the return type and the signature built above.
Reid Spencer30f9e27f2007-01-09 06:38:06 +00002327 printType(Out, RetTy,
Devang Patel05988662008-09-25 21:00:45 +00002328 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002329 FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002330}
2331
Reid Spencer22586642006-12-17 20:24:50 +00002332static inline bool isFPIntBitCast(const Instruction &I) {
2333 if (!isa<BitCastInst>(I))
2334 return false;
2335 const Type *SrcTy = I.getOperand(0)->getType();
2336 const Type *DstTy = I.getType();
Chris Lattner42a75512007-01-15 02:27:26 +00002337 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2338 (DstTy->isFloatingPoint() && SrcTy->isInteger());
Reid Spencer22586642006-12-17 20:24:50 +00002339}
2340
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002341void CWriter::printFunction(Function &F) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002342 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002343 bool isStructReturn = F.hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002344
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002345 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002346 Out << " {\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00002347
2348 // If this is a struct return function, handle the result with magic.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002349 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002350 const Type *StructTy =
2351 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2352 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002353 printType(Out, StructTy, false, "StructReturn");
Chris Lattner0c54d892006-05-23 23:39:48 +00002354 Out << "; /* Struct return temporary */\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002355
Chris Lattner0c54d892006-05-23 23:39:48 +00002356 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002357 printType(Out, F.arg_begin()->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002358 GetValueName(F.arg_begin()));
Chris Lattner0c54d892006-05-23 23:39:48 +00002359 Out << " = &StructReturn;\n";
2360 }
2361
2362 bool PrintedVar = false;
2363
Chris Lattner497e19a2002-05-09 20:39:03 +00002364 // print local variable information for the function
Reid Spencer941cfda2006-12-17 18:50:51 +00002365 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002366 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00002367 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002368 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00002369 Out << "; /* Address-exposed local */\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00002370 PrintedVar = true;
Chris Lattner6ffe5512004-04-27 15:13:33 +00002371 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00002372 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002373 printType(Out, I->getType(), false, GetValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002374 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002375
Chris Lattner84e66652003-05-03 07:11:00 +00002376 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2377 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002378 printType(Out, I->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002379 GetValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00002380 Out << ";\n";
2381 }
Chris Lattner0c54d892006-05-23 23:39:48 +00002382 PrintedVar = true;
Reid Spencer941cfda2006-12-17 18:50:51 +00002383 }
2384 // We need a temporary for the BitCast to use so it can pluck a value out
Reid Spencere4d87aa2006-12-23 06:05:41 +00002385 // of a union to do the BitCast. This is separate from the need for a
Reid Spencer941cfda2006-12-17 18:50:51 +00002386 // variable to hold the result of the BitCast.
Reid Spencer22586642006-12-17 20:24:50 +00002387 if (isFPIntBitCast(*I)) {
Bill Wendling145aad02007-02-23 22:45:08 +00002388 Out << " llvmBitCastUnion " << GetValueName(&*I)
Reid Spencer555a0b12006-12-11 20:39:15 +00002389 << "__BITCAST_TEMPORARY;\n";
Reid Spencer941cfda2006-12-17 18:50:51 +00002390 PrintedVar = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002391 }
Reid Spencer941cfda2006-12-17 18:50:51 +00002392 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002393
Chris Lattner0c54d892006-05-23 23:39:48 +00002394 if (PrintedVar)
2395 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002396
Chris Lattner395fd592004-12-13 21:52:52 +00002397 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00002398 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00002399
Chris Lattner16c7bb22002-05-09 02:28:59 +00002400 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002401 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002402 if (Loop *L = LI->getLoopFor(BB)) {
2403 if (L->getHeader() == BB && L->getParentLoop() == 0)
2404 printLoop(L);
2405 } else {
2406 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00002407 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002408 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002409
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002410 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002411}
2412
Chris Lattnercb3ad012004-05-09 20:41:32 +00002413void CWriter::printLoop(Loop *L) {
2414 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2415 << "' to make GCC happy */\n";
2416 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2417 BasicBlock *BB = L->getBlocks()[i];
2418 Loop *BBLoop = LI->getLoopFor(BB);
2419 if (BBLoop == L)
2420 printBasicBlock(BB);
2421 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00002422 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002423 }
2424 Out << " } while (1); /* end of syntactic loop '"
2425 << L->getHeader()->getName() << "' */\n";
2426}
2427
2428void CWriter::printBasicBlock(BasicBlock *BB) {
2429
2430 // Don't print the label for the basic block if there are no uses, or if
2431 // the only terminator use is the predecessor basic block's terminator.
2432 // We have to scan the use list because PHI nodes use basic blocks too but
2433 // do not require a label to be generated.
2434 //
2435 bool NeedsLabel = false;
2436 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2437 if (isGotoCodeNecessary(*PI, BB)) {
2438 NeedsLabel = true;
2439 break;
2440 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002441
Bill Wendling145aad02007-02-23 22:45:08 +00002442 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002443
Chris Lattnercb3ad012004-05-09 20:41:32 +00002444 // Output all of the instructions in the basic block...
2445 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2446 ++II) {
2447 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002448 if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
Chris Lattnercb3ad012004-05-09 20:41:32 +00002449 outputLValue(II);
2450 else
2451 Out << " ";
Chris Lattnere56d9462008-05-31 09:23:55 +00002452 writeInstComputationInline(*II);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002453 Out << ";\n";
2454 }
2455 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002456
Chris Lattnere56d9462008-05-31 09:23:55 +00002457 // Don't emit prefix or suffix for the terminator.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002458 visit(*BB->getTerminator());
2459}
2460
2461
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002462// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00002463// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002464//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002465void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002466 // If this is a struct return function, return the temporary struct.
Devang Patel41e23972008-03-03 21:46:28 +00002467 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002468
2469 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002470 Out << " return StructReturn;\n";
2471 return;
2472 }
2473
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002474 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00002475 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002476 &*--I.getParent()->getParent()->end() == I.getParent() &&
2477 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002478 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00002479 }
Chris Lattner44408262002-05-09 03:50:42 +00002480
Dan Gohman76612792008-04-23 21:49:29 +00002481 if (I.getNumOperands() > 1) {
2482 Out << " {\n";
2483 Out << " ";
2484 printType(Out, I.getParent()->getParent()->getReturnType());
2485 Out << " llvm_cbe_mrv_temp = {\n";
2486 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2487 Out << " ";
2488 writeOperand(I.getOperand(i));
2489 if (i != e - 1)
2490 Out << ",";
2491 Out << "\n";
2492 }
2493 Out << " };\n";
2494 Out << " return llvm_cbe_mrv_temp;\n";
2495 Out << " }\n";
2496 return;
2497 }
2498
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002499 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002500 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002501 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002502 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002503 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002504 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002505}
2506
Chris Lattnera9f5e052003-04-22 20:19:52 +00002507void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002508
Chris Lattnera9f5e052003-04-22 20:19:52 +00002509 Out << " switch (";
2510 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00002511 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00002512 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00002513 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002514 Out << ";\n";
2515 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2516 Out << " case ";
2517 writeOperand(SI.getOperand(i));
2518 Out << ":\n";
2519 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00002520 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002521 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattnerefd02c72005-03-19 17:35:11 +00002522 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00002523 Out << " break;\n";
2524 }
2525 Out << " }\n";
2526}
2527
Chris Lattnera9d12c02004-10-16 18:12:13 +00002528void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00002529 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00002530}
2531
Chris Lattnercb3ad012004-05-09 20:41:32 +00002532bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2533 /// FIXME: This should be reenabled, but loop reordering safe!!
2534 return true;
2535
Chris Lattner67c2d182005-03-18 16:12:37 +00002536 if (next(Function::iterator(From)) != Function::iterator(To))
2537 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002538
2539 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00002540
Chris Lattnercb3ad012004-05-09 20:41:32 +00002541 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002542 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002543 return false;
2544}
2545
John Criswell57bbfce2004-10-20 14:38:39 +00002546void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00002547 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00002548 unsigned Indent) {
2549 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2550 PHINode *PN = cast<PHINode>(I);
2551 // Now we have to do the printing.
2552 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2553 if (!isa<UndefValue>(IV)) {
2554 Out << std::string(Indent, ' ');
Bill Wendling145aad02007-02-23 22:45:08 +00002555 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
John Criswell57bbfce2004-10-20 14:38:39 +00002556 writeOperand(IV);
2557 Out << "; /* for PHI node */\n";
2558 }
2559 }
2560}
2561
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002562void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00002563 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002564 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00002565 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002566 writeOperand(Succ);
2567 Out << ";\n";
2568 }
2569}
2570
Misha Brukman37f92e22003-09-11 22:34:13 +00002571// Branch instruction printing - Avoid printing out a branch to a basic block
2572// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002573//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002574void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002575
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002576 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002577 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002578 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002579 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002580 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002581
John Criswell57bbfce2004-10-20 14:38:39 +00002582 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002583 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002584
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002585 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002586 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00002587 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002588 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002589 }
2590 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00002591 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002592 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002593 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002594 Out << ") {\n";
2595
John Criswell57bbfce2004-10-20 14:38:39 +00002596 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002597 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002598 }
2599
2600 Out << " }\n";
2601 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00002602 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002603 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002604 }
2605 Out << "\n";
2606}
2607
Chris Lattner84e66652003-05-03 07:11:00 +00002608// PHI nodes get copied into temporary values at the end of predecessor basic
2609// blocks. We now need to copy these temporary values into the REAL value for
2610// the PHI.
2611void CWriter::visitPHINode(PHINode &I) {
2612 writeOperand(&I);
2613 Out << "__PHI_TEMPORARY";
2614}
2615
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002616
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002617void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002618 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00002619 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00002620
2621 // We must cast the results of binary operations which might be promoted.
2622 bool needsCast = false;
Reid Spencer47857812006-12-31 05:55:36 +00002623 if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty)
Brian Gaekee99f4cf2003-06-25 03:05:33 +00002624 || (I.getType() == Type::FloatTy)) {
Brian Gaeke031a1122003-06-23 20:00:51 +00002625 needsCast = true;
2626 Out << "((";
Reid Spencer251f2142007-01-09 17:09:09 +00002627 printType(Out, I.getType(), false);
Brian Gaeke031a1122003-06-23 20:00:51 +00002628 Out << ")(";
2629 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002630
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002631 // If this is a negation operation, print it out as such. For FP, we don't
2632 // want to print "-0.0 - X".
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002633 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00002634 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002635 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00002636 Out << ")";
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002637 } else if (BinaryOperator::isFNeg(&I)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002638 Out << "-(";
2639 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2640 Out << ")";
Reid Spencer0a783f72006-11-02 01:53:59 +00002641 } else if (I.getOpcode() == Instruction::FRem) {
Chris Lattner57da2522005-08-23 20:22:50 +00002642 // Output a call to fmod/fmodf instead of emitting a%b
2643 if (I.getType() == Type::FloatTy)
2644 Out << "fmodf(";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00002645 else if (I.getType() == Type::DoubleTy)
Chris Lattner57da2522005-08-23 20:22:50 +00002646 Out << "fmod(";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00002647 else // all 3 flavors of long double
2648 Out << "fmodl(";
Chris Lattner57da2522005-08-23 20:22:50 +00002649 writeOperand(I.getOperand(0));
2650 Out << ", ";
2651 writeOperand(I.getOperand(1));
2652 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002653 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +00002654
2655 // Write out the cast of the instruction's value back to the proper type
2656 // if necessary.
2657 bool NeedsClosingParens = writeInstructionCast(I);
2658
2659 // Certain instructions require the operand to be forced to a specific type
2660 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2661 // below for operand 1
2662 writeOperandWithCast(I.getOperand(0), I.getOpcode());
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002663
2664 switch (I.getOpcode()) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002665 case Instruction::Add:
2666 case Instruction::FAdd: Out << " + "; break;
2667 case Instruction::Sub:
2668 case Instruction::FSub: Out << " - "; break;
2669 case Instruction::Mul:
2670 case Instruction::FMul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00002671 case Instruction::URem:
2672 case Instruction::SRem:
Reid Spencer832254e2007-02-02 02:16:23 +00002673 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00002674 case Instruction::UDiv:
2675 case Instruction::SDiv:
Reid Spencer832254e2007-02-02 02:16:23 +00002676 case Instruction::FDiv: Out << " / "; break;
2677 case Instruction::And: Out << " & "; break;
2678 case Instruction::Or: Out << " | "; break;
2679 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002680 case Instruction::Shl : Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00002681 case Instruction::LShr:
2682 case Instruction::AShr: Out << " >> "; break;
Torok Edwindac237e2009-07-08 20:53:28 +00002683 default:
2684#ifndef NDEBUG
2685 cerr << "Invalid operator type!" << I;
2686#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002687 llvm_unreachable(0);
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002688 }
2689
Reid Spencer1628cec2006-10-26 06:15:43 +00002690 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2691 if (NeedsClosingParens)
2692 Out << "))";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002693 }
2694
Brian Gaeke031a1122003-06-23 20:00:51 +00002695 if (needsCast) {
2696 Out << "))";
2697 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002698}
2699
Reid Spencere4d87aa2006-12-23 06:05:41 +00002700void CWriter::visitICmpInst(ICmpInst &I) {
2701 // We must cast the results of icmp which might be promoted.
2702 bool needsCast = false;
2703
2704 // Write out the cast of the instruction's value back to the proper type
2705 // if necessary.
2706 bool NeedsClosingParens = writeInstructionCast(I);
2707
2708 // Certain icmp predicate require the operand to be forced to a specific type
2709 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2710 // below for operand 1
Chris Lattner5bda9e42007-09-15 06:51:03 +00002711 writeOperandWithCast(I.getOperand(0), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002712
2713 switch (I.getPredicate()) {
2714 case ICmpInst::ICMP_EQ: Out << " == "; break;
2715 case ICmpInst::ICMP_NE: Out << " != "; break;
2716 case ICmpInst::ICMP_ULE:
2717 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2718 case ICmpInst::ICMP_UGE:
2719 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2720 case ICmpInst::ICMP_ULT:
2721 case ICmpInst::ICMP_SLT: Out << " < "; break;
2722 case ICmpInst::ICMP_UGT:
2723 case ICmpInst::ICMP_SGT: Out << " > "; break;
Torok Edwindac237e2009-07-08 20:53:28 +00002724 default:
2725#ifndef NDEBUG
2726 cerr << "Invalid icmp predicate!" << I;
2727#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002728 llvm_unreachable(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002729 }
2730
Chris Lattner5bda9e42007-09-15 06:51:03 +00002731 writeOperandWithCast(I.getOperand(1), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002732 if (NeedsClosingParens)
2733 Out << "))";
2734
2735 if (needsCast) {
2736 Out << "))";
2737 }
2738}
2739
2740void CWriter::visitFCmpInst(FCmpInst &I) {
Reid Spencerb801a272007-01-08 06:58:32 +00002741 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2742 Out << "0";
2743 return;
2744 }
2745 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2746 Out << "1";
2747 return;
2748 }
2749
2750 const char* op = 0;
2751 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002752 default: llvm_unreachable("Illegal FCmp predicate");
Reid Spencerb801a272007-01-08 06:58:32 +00002753 case FCmpInst::FCMP_ORD: op = "ord"; break;
2754 case FCmpInst::FCMP_UNO: op = "uno"; break;
2755 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2756 case FCmpInst::FCMP_UNE: op = "une"; break;
2757 case FCmpInst::FCMP_ULT: op = "ult"; break;
2758 case FCmpInst::FCMP_ULE: op = "ule"; break;
2759 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2760 case FCmpInst::FCMP_UGE: op = "uge"; break;
2761 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2762 case FCmpInst::FCMP_ONE: op = "one"; break;
2763 case FCmpInst::FCMP_OLT: op = "olt"; break;
2764 case FCmpInst::FCMP_OLE: op = "ole"; break;
2765 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2766 case FCmpInst::FCMP_OGE: op = "oge"; break;
2767 }
2768
2769 Out << "llvm_fcmp_" << op << "(";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002770 // Write the first operand
2771 writeOperand(I.getOperand(0));
Reid Spencerb801a272007-01-08 06:58:32 +00002772 Out << ", ";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002773 // Write the second operand
2774 writeOperand(I.getOperand(1));
Reid Spencerb801a272007-01-08 06:58:32 +00002775 Out << ")";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002776}
2777
Reid Spencer555a0b12006-12-11 20:39:15 +00002778static const char * getFloatBitCastField(const Type *Ty) {
2779 switch (Ty->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002780 default: llvm_unreachable("Invalid Type");
Reid Spencer47857812006-12-31 05:55:36 +00002781 case Type::FloatTyID: return "Float";
Reid Spencer47857812006-12-31 05:55:36 +00002782 case Type::DoubleTyID: return "Double";
Reid Spencera54b7cb2007-01-12 07:05:14 +00002783 case Type::IntegerTyID: {
2784 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2785 if (NumBits <= 32)
2786 return "Int32";
2787 else
2788 return "Int64";
2789 }
Reid Spencer555a0b12006-12-11 20:39:15 +00002790 }
2791}
2792
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002793void CWriter::visitCastInst(CastInst &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002794 const Type *DstTy = I.getType();
2795 const Type *SrcTy = I.getOperand(0)->getType();
Reid Spencer22586642006-12-17 20:24:50 +00002796 if (isFPIntBitCast(I)) {
Chris Lattnere56d9462008-05-31 09:23:55 +00002797 Out << '(';
Reid Spencer555a0b12006-12-11 20:39:15 +00002798 // These int<->float and long<->double casts need to be handled specially
Bill Wendling145aad02007-02-23 22:45:08 +00002799 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002800 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2801 writeOperand(I.getOperand(0));
Bill Wendling145aad02007-02-23 22:45:08 +00002802 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002803 << getFloatBitCastField(I.getType());
Chris Lattnere56d9462008-05-31 09:23:55 +00002804 Out << ')';
2805 return;
2806 }
2807
2808 Out << '(';
2809 printCast(I.getOpcode(), SrcTy, DstTy);
2810
2811 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
2812 if (SrcTy == Type::Int1Ty && I.getOpcode() == Instruction::SExt)
2813 Out << "0-";
2814
2815 writeOperand(I.getOperand(0));
2816
2817 if (DstTy == Type::Int1Ty &&
2818 (I.getOpcode() == Instruction::Trunc ||
2819 I.getOpcode() == Instruction::FPToUI ||
2820 I.getOpcode() == Instruction::FPToSI ||
2821 I.getOpcode() == Instruction::PtrToInt)) {
2822 // Make sure we really get a trunc to bool by anding the operand with 1
2823 Out << "&1u";
Reid Spencer3da59db2006-11-27 01:05:10 +00002824 }
Chris Lattner72623362007-05-03 02:57:13 +00002825 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002826}
2827
Chris Lattner9f24a072004-03-12 05:52:14 +00002828void CWriter::visitSelectInst(SelectInst &I) {
2829 Out << "((";
2830 writeOperand(I.getCondition());
2831 Out << ") ? (";
2832 writeOperand(I.getTrueValue());
2833 Out << ") : (";
2834 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00002835 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00002836}
2837
2838
Chris Lattnerc2421432004-05-09 04:30:20 +00002839void CWriter::lowerIntrinsics(Function &F) {
Reid Spencer69f80a62007-04-12 21:00:45 +00002840 // This is used to keep track of intrinsics that get generated to a lowered
2841 // function. We must generate the prototypes before the function body which
2842 // will only be expanded on first use (by the loop below).
2843 std::vector<Function*> prototypesToGen;
2844
2845 // Examine all the instructions in this function to find the intrinsics that
2846 // need to be lowered.
Jeff Cohen614408d2007-04-13 22:52:03 +00002847 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
Chris Lattnerc2421432004-05-09 04:30:20 +00002848 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2849 if (CallInst *CI = dyn_cast<CallInst>(I++))
2850 if (Function *F = CI->getCalledFunction())
2851 switch (F->getIntrinsicID()) {
2852 case Intrinsic::not_intrinsic:
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00002853 case Intrinsic::memory_barrier:
Chris Lattnerc2421432004-05-09 04:30:20 +00002854 case Intrinsic::vastart:
2855 case Intrinsic::vacopy:
2856 case Intrinsic::vaend:
2857 case Intrinsic::returnaddress:
2858 case Intrinsic::frameaddress:
2859 case Intrinsic::setjmp:
2860 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00002861 case Intrinsic::prefetch:
Jim Laskey7075d6f2006-03-08 19:31:15 +00002862 case Intrinsic::dbg_stoppoint:
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00002863 case Intrinsic::powi:
Chris Lattner4e220122008-03-02 08:47:13 +00002864 case Intrinsic::x86_sse_cmp_ss:
2865 case Intrinsic::x86_sse_cmp_ps:
2866 case Intrinsic::x86_sse2_cmp_sd:
2867 case Intrinsic::x86_sse2_cmp_pd:
Chris Lattnerff939212008-03-02 08:54:27 +00002868 case Intrinsic::ppc_altivec_lvsl:
Chris Lattner4e220122008-03-02 08:47:13 +00002869 // We directly implement these intrinsics
Chris Lattnerc2421432004-05-09 04:30:20 +00002870 break;
2871 default:
Chris Lattner87242152006-03-13 23:09:05 +00002872 // If this is an intrinsic that directly corresponds to a GCC
2873 // builtin, we handle it.
2874 const char *BuiltinName = "";
2875#define GET_GCC_BUILTIN_NAME
2876#include "llvm/Intrinsics.gen"
2877#undef GET_GCC_BUILTIN_NAME
2878 // If we handle it, don't lower it.
2879 if (BuiltinName[0]) break;
2880
Chris Lattnerc2421432004-05-09 04:30:20 +00002881 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00002882 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002883 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00002884 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00002885
Reid Spencer519e2392007-01-29 17:51:02 +00002886 IL->LowerIntrinsicCall(CI);
Chris Lattnerc2421432004-05-09 04:30:20 +00002887 if (Before) { // Move iterator to instruction after call
2888 I = Before; ++I;
2889 } else {
2890 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00002891 }
Reid Spencer69f80a62007-04-12 21:00:45 +00002892 // If the intrinsic got lowered to another call, and that call has
2893 // a definition then we need to make sure its prototype is emitted
2894 // before any calls to it.
2895 if (CallInst *Call = dyn_cast<CallInst>(I))
2896 if (Function *NewF = Call->getCalledFunction())
2897 if (!NewF->isDeclaration())
2898 prototypesToGen.push_back(NewF);
2899
Chris Lattner87242152006-03-13 23:09:05 +00002900 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00002901 }
Chris Lattner4ef51372004-02-14 00:31:10 +00002902
Reid Spencer69f80a62007-04-12 21:00:45 +00002903 // We may have collected some prototypes to emit in the loop above.
2904 // Emit them now, before the function that uses them is emitted. But,
2905 // be careful not to emit them twice.
2906 std::vector<Function*>::iterator I = prototypesToGen.begin();
2907 std::vector<Function*>::iterator E = prototypesToGen.end();
2908 for ( ; I != E; ++I) {
Reid Spencer57c5b182007-04-12 21:57:15 +00002909 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
Reid Spencer69f80a62007-04-12 21:00:45 +00002910 Out << '\n';
2911 printFunctionSignature(*I, true);
2912 Out << ";\n";
Reid Spencer69f80a62007-04-12 21:00:45 +00002913 }
2914 }
2915}
Chris Lattner4ef51372004-02-14 00:31:10 +00002916
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002917void CWriter::visitCallInst(CallInst &I) {
Chris Lattnerf6a048c2008-05-22 06:19:37 +00002918 if (isa<InlineAsm>(I.getOperand(0)))
2919 return visitInlineAsm(I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002920
Chris Lattner87242152006-03-13 23:09:05 +00002921 bool WroteCallee = false;
2922
Chris Lattner18ac3c82003-05-08 18:41:45 +00002923 // Handle intrinsic function calls first...
2924 if (Function *F = I.getCalledFunction())
Chris Lattner2299fec2008-03-02 08:29:41 +00002925 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2926 if (visitBuiltinCall(I, ID, WroteCallee))
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00002927 return;
Chris Lattner18ac3c82003-05-08 18:41:45 +00002928
Chris Lattner4394d512004-11-13 22:21:56 +00002929 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00002930
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002931 const PointerType *PTy = cast<PointerType>(Callee->getType());
2932 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2933
Chris Lattner0c54d892006-05-23 23:39:48 +00002934 // If this is a call to a struct-return function, assign to the first
2935 // parameter instead of passing it to the call.
Devang Patel05988662008-09-25 21:00:45 +00002936 const AttrListPtr &PAL = I.getAttributes();
Evan Cheng7723ab32008-01-12 18:53:07 +00002937 bool hasByVal = I.hasByValArgument();
Devang Patel41e23972008-03-03 21:46:28 +00002938 bool isStructRet = I.hasStructRetAttr();
Chris Lattner0c54d892006-05-23 23:39:48 +00002939 if (isStructRet) {
Chris Lattnere05252b42008-03-02 08:07:24 +00002940 writeOperandDeref(I.getOperand(1));
Evan Cheng3d794782008-01-11 23:10:11 +00002941 Out << " = ";
Chris Lattner0c54d892006-05-23 23:39:48 +00002942 }
2943
Chris Lattnerfe673d92005-05-06 06:53:07 +00002944 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattner0c54d892006-05-23 23:39:48 +00002945
2946 if (!WroteCallee) {
2947 // If this is an indirect call to a struct return function, we need to cast
Evan Cheng7723ab32008-01-12 18:53:07 +00002948 // the pointer. Ditto for indirect calls with byval arguments.
2949 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002950
Chris Lattner0c54d892006-05-23 23:39:48 +00002951 // GCC is a real PITA. It does not permit codegening casts of functions to
2952 // function pointers if they are in a call (it generates a trap instruction
2953 // instead!). We work around this by inserting a cast to void* in between
2954 // the function and the function pointer cast. Unfortunately, we can't just
2955 // form the constant expression here, because the folder will immediately
2956 // nuke it.
2957 //
2958 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2959 // that void* and function pointers have the same size. :( To deal with this
2960 // in the common case, we handle casts where the number of arguments passed
2961 // match exactly.
2962 //
2963 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
Reid Spencer3da59db2006-11-27 01:05:10 +00002964 if (CE->isCast())
Chris Lattner0c54d892006-05-23 23:39:48 +00002965 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2966 NeedsCast = true;
2967 Callee = RF;
2968 }
2969
2970 if (NeedsCast) {
2971 // Ok, just cast the pointer type.
2972 Out << "((";
Evan Cheng7723ab32008-01-12 18:53:07 +00002973 if (isStructRet)
Duncan Sandsdc024672007-11-27 13:23:08 +00002974 printStructReturnPointerFunctionType(Out, PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +00002975 cast<PointerType>(I.getCalledValue()->getType()));
Evan Cheng7723ab32008-01-12 18:53:07 +00002976 else if (hasByVal)
2977 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
2978 else
2979 printType(Out, I.getCalledValue()->getType());
Chris Lattner0c54d892006-05-23 23:39:48 +00002980 Out << ")(void*)";
2981 }
2982 writeOperand(Callee);
2983 if (NeedsCast) Out << ')';
2984 }
2985
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002986 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002987
Chris Lattner4394d512004-11-13 22:21:56 +00002988 unsigned NumDeclaredParams = FTy->getNumParams();
2989
Chris Lattner0c54d892006-05-23 23:39:48 +00002990 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2991 unsigned ArgNo = 0;
2992 if (isStructRet) { // Skip struct return argument.
2993 ++AI;
2994 ++ArgNo;
2995 }
2996
2997 bool PrintedArg = false;
Evan Cheng3d794782008-01-11 23:10:11 +00002998 for (; AI != AE; ++AI, ++ArgNo) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002999 if (PrintedArg) Out << ", ";
3000 if (ArgNo < NumDeclaredParams &&
3001 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003002 Out << '(';
Reid Spencer0ae96932007-01-07 03:24:48 +00003003 printType(Out, FTy->getParamType(ArgNo),
Devang Patel05988662008-09-25 21:00:45 +00003004 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003005 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00003006 }
Evan Cheng3d794782008-01-11 23:10:11 +00003007 // Check if the argument is expected to be passed by value.
Devang Patel05988662008-09-25 21:00:45 +00003008 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
Chris Lattnere05252b42008-03-02 08:07:24 +00003009 writeOperandDeref(*AI);
3010 else
3011 writeOperand(*AI);
Chris Lattner0c54d892006-05-23 23:39:48 +00003012 PrintedArg = true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003013 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003014 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00003015}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003016
Chris Lattner2299fec2008-03-02 08:29:41 +00003017/// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3018/// if the entire call is handled, return false it it wasn't handled, and
3019/// optionally set 'WroteCallee' if the callee has already been printed out.
3020bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3021 bool &WroteCallee) {
3022 switch (ID) {
3023 default: {
3024 // If this is an intrinsic that directly corresponds to a GCC
3025 // builtin, we emit it here.
3026 const char *BuiltinName = "";
3027 Function *F = I.getCalledFunction();
3028#define GET_GCC_BUILTIN_NAME
3029#include "llvm/Intrinsics.gen"
3030#undef GET_GCC_BUILTIN_NAME
3031 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3032
3033 Out << BuiltinName;
3034 WroteCallee = true;
3035 return false;
3036 }
3037 case Intrinsic::memory_barrier:
Andrew Lenharth6ad150b2008-03-05 23:41:37 +00003038 Out << "__sync_synchronize()";
Chris Lattner2299fec2008-03-02 08:29:41 +00003039 return true;
3040 case Intrinsic::vastart:
3041 Out << "0; ";
3042
3043 Out << "va_start(*(va_list*)";
3044 writeOperand(I.getOperand(1));
3045 Out << ", ";
3046 // Output the last argument to the enclosing function.
3047 if (I.getParent()->getParent()->arg_empty()) {
Torok Edwindac237e2009-07-08 20:53:28 +00003048 std::string msg;
3049 raw_string_ostream Msg(msg);
3050 Msg << "The C backend does not currently support zero "
Chris Lattner2299fec2008-03-02 08:29:41 +00003051 << "argument varargs functions, such as '"
Torok Edwindac237e2009-07-08 20:53:28 +00003052 << I.getParent()->getParent()->getName() << "'!";
3053 llvm_report_error(Msg.str());
Chris Lattner2299fec2008-03-02 08:29:41 +00003054 }
3055 writeOperand(--I.getParent()->getParent()->arg_end());
3056 Out << ')';
3057 return true;
3058 case Intrinsic::vaend:
3059 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3060 Out << "0; va_end(*(va_list*)";
3061 writeOperand(I.getOperand(1));
3062 Out << ')';
3063 } else {
3064 Out << "va_end(*(va_list*)0)";
3065 }
3066 return true;
3067 case Intrinsic::vacopy:
3068 Out << "0; ";
3069 Out << "va_copy(*(va_list*)";
3070 writeOperand(I.getOperand(1));
3071 Out << ", *(va_list*)";
3072 writeOperand(I.getOperand(2));
3073 Out << ')';
3074 return true;
3075 case Intrinsic::returnaddress:
3076 Out << "__builtin_return_address(";
3077 writeOperand(I.getOperand(1));
3078 Out << ')';
3079 return true;
3080 case Intrinsic::frameaddress:
3081 Out << "__builtin_frame_address(";
3082 writeOperand(I.getOperand(1));
3083 Out << ')';
3084 return true;
3085 case Intrinsic::powi:
3086 Out << "__builtin_powi(";
3087 writeOperand(I.getOperand(1));
3088 Out << ", ";
3089 writeOperand(I.getOperand(2));
3090 Out << ')';
3091 return true;
3092 case Intrinsic::setjmp:
3093 Out << "setjmp(*(jmp_buf*)";
3094 writeOperand(I.getOperand(1));
3095 Out << ')';
3096 return true;
3097 case Intrinsic::longjmp:
3098 Out << "longjmp(*(jmp_buf*)";
3099 writeOperand(I.getOperand(1));
3100 Out << ", ";
3101 writeOperand(I.getOperand(2));
3102 Out << ')';
3103 return true;
3104 case Intrinsic::prefetch:
3105 Out << "LLVM_PREFETCH((const void *)";
3106 writeOperand(I.getOperand(1));
3107 Out << ", ";
3108 writeOperand(I.getOperand(2));
3109 Out << ", ";
3110 writeOperand(I.getOperand(3));
3111 Out << ")";
3112 return true;
3113 case Intrinsic::stacksave:
3114 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3115 // to work around GCC bugs (see PR1809).
3116 Out << "0; *((void**)&" << GetValueName(&I)
3117 << ") = __builtin_stack_save()";
3118 return true;
3119 case Intrinsic::dbg_stoppoint: {
3120 // If we use writeOperand directly we get a "u" suffix which is rejected
3121 // by gcc.
Owen Andersoncb371882008-08-21 00:14:44 +00003122 std::stringstream SPIStr;
Chris Lattner2299fec2008-03-02 08:29:41 +00003123 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Owen Andersoncb371882008-08-21 00:14:44 +00003124 SPI.getDirectory()->print(SPIStr);
Chris Lattner2299fec2008-03-02 08:29:41 +00003125 Out << "\n#line "
3126 << SPI.getLine()
Owen Andersoncb371882008-08-21 00:14:44 +00003127 << " \"";
3128 Out << SPIStr.str();
3129 SPIStr.clear();
3130 SPI.getFileName()->print(SPIStr);
3131 Out << SPIStr.str() << "\"\n";
Chris Lattner2299fec2008-03-02 08:29:41 +00003132 return true;
3133 }
Chris Lattner4e220122008-03-02 08:47:13 +00003134 case Intrinsic::x86_sse_cmp_ss:
3135 case Intrinsic::x86_sse_cmp_ps:
3136 case Intrinsic::x86_sse2_cmp_sd:
3137 case Intrinsic::x86_sse2_cmp_pd:
3138 Out << '(';
3139 printType(Out, I.getType());
3140 Out << ')';
3141 // Multiple GCC builtins multiplex onto this intrinsic.
3142 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003143 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
Chris Lattner4e220122008-03-02 08:47:13 +00003144 case 0: Out << "__builtin_ia32_cmpeq"; break;
3145 case 1: Out << "__builtin_ia32_cmplt"; break;
3146 case 2: Out << "__builtin_ia32_cmple"; break;
3147 case 3: Out << "__builtin_ia32_cmpunord"; break;
3148 case 4: Out << "__builtin_ia32_cmpneq"; break;
3149 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3150 case 6: Out << "__builtin_ia32_cmpnle"; break;
3151 case 7: Out << "__builtin_ia32_cmpord"; break;
3152 }
3153 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3154 Out << 'p';
3155 else
3156 Out << 's';
3157 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3158 Out << 's';
3159 else
3160 Out << 'd';
3161
3162 Out << "(";
3163 writeOperand(I.getOperand(1));
3164 Out << ", ";
3165 writeOperand(I.getOperand(2));
3166 Out << ")";
3167 return true;
Chris Lattnerff939212008-03-02 08:54:27 +00003168 case Intrinsic::ppc_altivec_lvsl:
3169 Out << '(';
3170 printType(Out, I.getType());
3171 Out << ')';
3172 Out << "__builtin_altivec_lvsl(0, (void*)";
3173 writeOperand(I.getOperand(1));
3174 Out << ")";
3175 return true;
Chris Lattner2299fec2008-03-02 08:29:41 +00003176 }
3177}
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003178
3179//This converts the llvm constraint string to something gcc is expecting.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003180//TODO: work out platform independent constraints and factor those out
Andrew Lenharth238581f2006-11-28 19:56:02 +00003181// of the per target tables
3182// handle multiple constraint codes
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003183std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003184
3185 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3186
Dan Gohmancfbb2f02008-03-25 21:45:14 +00003187 const char *const *table = 0;
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003188
3189 //Grab the translation table from TargetAsmInfo if it exists
3190 if (!TAsm) {
3191 std::string E;
Gordon Henriksen4b2b9402007-10-17 21:28:48 +00003192 const TargetMachineRegistry::entry* Match =
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003193 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
3194 if (Match) {
3195 //Per platform Target Machines don't exist, so create it
3196 // this must be done only once
3197 const TargetMachine* TM = Match->CtorFn(*TheModule, "");
3198 TAsm = TM->getTargetAsmInfo();
3199 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003200 }
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003201 if (TAsm)
3202 table = TAsm->getAsmCBE();
3203
3204 //Search the translation table if it exists
3205 for (int i = 0; table && table[i]; i += 2)
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003206 if (c.Codes[0] == table[i])
3207 return table[i+1];
3208
Andrew Lenharth85f22282006-11-28 22:25:32 +00003209 //default is identity
3210 return c.Codes[0];
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003211}
3212
3213//TODO: import logic from AsmPrinter.cpp
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003214static std::string gccifyAsm(std::string asmstr) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003215 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3216 if (asmstr[i] == '\n')
3217 asmstr.replace(i, 1, "\\n");
3218 else if (asmstr[i] == '\t')
3219 asmstr.replace(i, 1, "\\t");
3220 else if (asmstr[i] == '$') {
3221 if (asmstr[i + 1] == '{') {
3222 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3223 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3224 std::string n = "%" +
3225 asmstr.substr(a + 1, b - a - 1) +
3226 asmstr.substr(i + 2, a - i - 2);
3227 asmstr.replace(i, b - i + 1, n);
3228 i += n.size() - 1;
3229 } else
3230 asmstr.replace(i, 1, "%");
3231 }
3232 else if (asmstr[i] == '%')//grr
3233 { asmstr.replace(i, 1, "%%"); ++i;}
3234
3235 return asmstr;
3236}
3237
Andrew Lenharth238581f2006-11-28 19:56:02 +00003238//TODO: assumptions about what consume arguments from the call are likely wrong
3239// handle communitivity
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003240void CWriter::visitInlineAsm(CallInst &CI) {
3241 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003242 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003243
3244 std::vector<std::pair<Value*, int> > ResultVals;
3245 if (CI.getType() == Type::VoidTy)
3246 ;
3247 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3248 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3249 ResultVals.push_back(std::make_pair(&CI, (int)i));
3250 } else {
3251 ResultVals.push_back(std::make_pair(&CI, -1));
3252 }
3253
Chris Lattner67f631d2008-06-04 18:03:28 +00003254 // Fix up the asm string for gcc and emit it.
3255 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3256 Out << " :";
3257
3258 unsigned ValueCount = 0;
3259 bool IsFirst = true;
3260
3261 // Convert over all the output constraints.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003262 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
Chris Lattner67f631d2008-06-04 18:03:28 +00003263 E = Constraints.end(); I != E; ++I) {
3264
3265 if (I->Type != InlineAsm::isOutput) {
3266 ++ValueCount;
3267 continue; // Ignore non-output constraints.
3268 }
3269
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003270 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003271 std::string C = InterpretASMConstraint(*I);
3272 if (C.empty()) continue;
3273
Chris Lattner67f631d2008-06-04 18:03:28 +00003274 if (!IsFirst) {
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003275 Out << ", ";
Chris Lattner67f631d2008-06-04 18:03:28 +00003276 IsFirst = false;
3277 }
3278
3279 // Unpack the dest.
3280 Value *DestVal;
3281 int DestValNo = -1;
3282
3283 if (ValueCount < ResultVals.size()) {
3284 DestVal = ResultVals[ValueCount].first;
3285 DestValNo = ResultVals[ValueCount].second;
3286 } else
3287 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3288
3289 if (I->isEarlyClobber)
3290 C = "&"+C;
3291
3292 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3293 if (DestValNo != -1)
3294 Out << ".field" << DestValNo; // Multiple retvals.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003295 Out << ")";
Chris Lattner67f631d2008-06-04 18:03:28 +00003296 ++ValueCount;
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003297 }
Chris Lattner67f631d2008-06-04 18:03:28 +00003298
3299
3300 // Convert over all the input constraints.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003301 Out << "\n :";
Chris Lattner67f631d2008-06-04 18:03:28 +00003302 IsFirst = true;
3303 ValueCount = 0;
3304 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3305 E = Constraints.end(); I != E; ++I) {
3306 if (I->Type != InlineAsm::isInput) {
3307 ++ValueCount;
3308 continue; // Ignore non-input constraints.
3309 }
3310
3311 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3312 std::string C = InterpretASMConstraint(*I);
3313 if (C.empty()) continue;
3314
3315 if (!IsFirst) {
Chris Lattner687a4cb2008-05-22 06:29:38 +00003316 Out << ", ";
Chris Lattner67f631d2008-06-04 18:03:28 +00003317 IsFirst = false;
3318 }
3319
3320 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3321 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3322
3323 Out << "\"" << C << "\"(";
3324 if (!I->isIndirect)
3325 writeOperand(SrcVal);
3326 else
3327 writeOperandDeref(SrcVal);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003328 Out << ")";
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003329 }
Chris Lattner67f631d2008-06-04 18:03:28 +00003330
3331 // Convert over the clobber constraints.
3332 IsFirst = true;
3333 ValueCount = 0;
3334 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3335 E = Constraints.end(); I != E; ++I) {
3336 if (I->Type != InlineAsm::isClobber)
3337 continue; // Ignore non-input constraints.
3338
3339 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3340 std::string C = InterpretASMConstraint(*I);
3341 if (C.empty()) continue;
3342
3343 if (!IsFirst) {
3344 Out << ", ";
3345 IsFirst = false;
3346 }
3347
3348 Out << '\"' << C << '"';
3349 }
3350
Andrew Lenharthf45148e2006-11-28 23:07:32 +00003351 Out << ")";
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003352}
3353
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003354void CWriter::visitMallocInst(MallocInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003355 llvm_unreachable("lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003356}
3357
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003358void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003359 Out << '(';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00003360 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003361 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00003362 printType(Out, I.getType()->getElementType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003363 Out << ')';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003364 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003365 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003366 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003367 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003368 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003369}
3370
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003371void CWriter::visitFreeInst(FreeInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003372 llvm_unreachable("lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003373}
3374
Chris Lattnere05252b42008-03-02 08:07:24 +00003375void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohman9f8d5712008-07-24 17:57:48 +00003376 gep_type_iterator E, bool Static) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003377
3378 // If there are no indices, just print out the pointer.
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00003379 if (I == E) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003380 writeOperand(Ptr);
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00003381 return;
3382 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003383
3384 // Find out if the last index is into a vector. If so, we have to print this
3385 // specially. Since vectors can't have elements of indexable type, only the
3386 // last index could possibly be of a vector element.
3387 const VectorType *LastIndexIsVector = 0;
3388 {
3389 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3390 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
Nick Hildenbrandte548f002002-09-25 20:29:26 +00003391 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003392
3393 Out << "(";
3394
3395 // If the last index is into a vector, we can't print it as &a[i][j] because
3396 // we can't index into a vector with j in GCC. Instead, emit this as
3397 // (((float*)&a[i])+j)
3398 if (LastIndexIsVector) {
3399 Out << "((";
3400 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3401 Out << ")(";
3402 }
3403
3404 Out << '&';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003405
Chris Lattnere05252b42008-03-02 08:07:24 +00003406 // If the first index is 0 (very typical) we can do a number of
3407 // simplifications to clean up the code.
3408 Value *FirstOp = I.getOperand();
3409 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3410 // First index isn't simple, print it the hard way.
3411 writeOperand(Ptr);
3412 } else {
3413 ++I; // Skip the zero index.
Nick Hildenbrandte548f002002-09-25 20:29:26 +00003414
Chris Lattnere05252b42008-03-02 08:07:24 +00003415 // Okay, emit the first operand. If Ptr is something that is already address
3416 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3417 if (isAddressExposed(Ptr)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00003418 writeOperandInternal(Ptr, Static);
Chris Lattnere05252b42008-03-02 08:07:24 +00003419 } else if (I != E && isa<StructType>(*I)) {
3420 // If we didn't already emit the first operand, see if we can print it as
3421 // P->f instead of "P[0].f"
3422 writeOperand(Ptr);
3423 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3424 ++I; // eat the struct index as well.
3425 } else {
3426 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3427 Out << "(*";
3428 writeOperand(Ptr);
3429 Out << ")";
Chris Lattner23e90702003-11-25 20:49:55 +00003430 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003431 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00003432
Chris Lattnere05252b42008-03-02 08:07:24 +00003433 for (; I != E; ++I) {
Chris Lattner23e90702003-11-25 20:49:55 +00003434 if (isa<StructType>(*I)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003435 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
Dan Gohman193c2352008-06-02 21:30:49 +00003436 } else if (isa<ArrayType>(*I)) {
3437 Out << ".array[";
3438 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3439 Out << ']';
Chris Lattnere05252b42008-03-02 08:07:24 +00003440 } else if (!isa<VectorType>(*I)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003441 Out << '[';
Chris Lattner96b207c2007-09-22 20:16:48 +00003442 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003443 Out << ']';
Chris Lattnere05252b42008-03-02 08:07:24 +00003444 } else {
3445 // If the last index is into a vector, then print it out as "+j)". This
3446 // works with the 'LastIndexIsVector' code above.
3447 if (isa<Constant>(I.getOperand()) &&
3448 cast<Constant>(I.getOperand())->isNullValue()) {
3449 Out << "))"; // avoid "+0".
3450 } else {
3451 Out << ")+(";
3452 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3453 Out << "))";
3454 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003455 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003456 }
3457 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003458}
3459
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003460void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3461 bool IsVolatile, unsigned Alignment) {
3462
3463 bool IsUnaligned = Alignment &&
3464 Alignment < TD->getABITypeAlignment(OperandType);
3465
3466 if (!IsUnaligned)
3467 Out << '*';
3468 if (IsVolatile || IsUnaligned) {
Chris Lattner8399e022005-02-15 05:52:14 +00003469 Out << "((";
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003470 if (IsUnaligned)
3471 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3472 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3473 if (IsUnaligned) {
3474 Out << "; } ";
3475 if (IsVolatile) Out << "volatile ";
3476 Out << "*";
3477 }
Chris Lattnerb94388a2005-09-27 20:52:44 +00003478 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00003479 }
3480
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003481 writeOperand(Operand);
Chris Lattner9d30e222005-02-14 16:47:52 +00003482
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003483 if (IsVolatile || IsUnaligned) {
Misha Brukman23ba0c52005-03-08 00:26:08 +00003484 Out << ')';
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003485 if (IsUnaligned)
3486 Out << "->data";
3487 }
3488}
3489
3490void CWriter::visitLoadInst(LoadInst &I) {
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003491 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3492 I.getAlignment());
3493
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003494}
3495
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003496void CWriter::visitStoreInst(StoreInst &I) {
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003497 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3498 I.isVolatile(), I.getAlignment());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003499 Out << " = ";
Reid Spencerbdc75082007-03-03 16:33:33 +00003500 Value *Operand = I.getOperand(0);
3501 Constant *BitMask = 0;
3502 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3503 if (!ITy->isPowerOf2ByteWidth())
3504 // We have a bit width that doesn't match an even power-of-2 byte
3505 // size. Consequently we must & the value with the type's bit mask
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003506 BitMask = Context->getConstantInt(ITy, ITy->getBitMask());
Reid Spencerbdc75082007-03-03 16:33:33 +00003507 if (BitMask)
3508 Out << "((";
3509 writeOperand(Operand);
3510 if (BitMask) {
3511 Out << ") & ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00003512 printConstant(BitMask, false);
Reid Spencerbdc75082007-03-03 16:33:33 +00003513 Out << ")";
3514 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003515}
3516
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003517void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003518 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
Dan Gohman9f8d5712008-07-24 17:57:48 +00003519 gep_type_end(I), false);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003520}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00003521
Chris Lattner4d45bd02003-10-18 05:57:43 +00003522void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00003523 Out << "va_arg(*(va_list*)";
Chris Lattner4d45bd02003-10-18 05:57:43 +00003524 writeOperand(I.getOperand(0));
Andrew Lenharth558bc882005-06-18 18:34:52 +00003525 Out << ", ";
Chris Lattner7635ea42003-11-03 01:01:59 +00003526 printType(Out, I.getType());
Andrew Lenharth558bc882005-06-18 18:34:52 +00003527 Out << ");\n ";
Chris Lattner4d45bd02003-10-18 05:57:43 +00003528}
3529
Chris Lattner33a44d92008-03-02 03:52:39 +00003530void CWriter::visitInsertElementInst(InsertElementInst &I) {
3531 const Type *EltTy = I.getType()->getElementType();
3532 writeOperand(I.getOperand(0));
3533 Out << ";\n ";
3534 Out << "((";
3535 printType(Out, PointerType::getUnqual(EltTy));
3536 Out << ")(&" << GetValueName(&I) << "))[";
Chris Lattner33a44d92008-03-02 03:52:39 +00003537 writeOperand(I.getOperand(2));
Chris Lattner9152daf2008-03-02 08:10:16 +00003538 Out << "] = (";
3539 writeOperand(I.getOperand(1));
Chris Lattner33a44d92008-03-02 03:52:39 +00003540 Out << ")";
3541}
3542
Chris Lattner0452ed62008-03-02 03:57:08 +00003543void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3544 // We know that our operand is not inlined.
3545 Out << "((";
3546 const Type *EltTy =
3547 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3548 printType(Out, PointerType::getUnqual(EltTy));
3549 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3550 writeOperand(I.getOperand(1));
3551 Out << "]";
3552}
3553
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003554void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3555 Out << "(";
3556 printType(Out, SVI.getType());
3557 Out << "){ ";
3558 const VectorType *VT = SVI.getType();
3559 unsigned NumElts = VT->getNumElements();
3560 const Type *EltTy = VT->getElementType();
3561
3562 for (unsigned i = 0; i != NumElts; ++i) {
3563 if (i) Out << ", ";
3564 int SrcVal = SVI.getMaskValue(i);
3565 if ((unsigned)SrcVal >= NumElts*2) {
3566 Out << " 0/*undef*/ ";
3567 } else {
3568 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3569 if (isa<Instruction>(Op)) {
3570 // Do an extractelement of this value from the appropriate input.
3571 Out << "((";
3572 printType(Out, PointerType::getUnqual(EltTy));
3573 Out << ")(&" << GetValueName(Op)
Duncan Sands43e2a032008-05-27 11:50:51 +00003574 << "))[" << (SrcVal & (NumElts-1)) << "]";
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003575 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3576 Out << "0";
3577 } else {
Duncan Sands43e2a032008-05-27 11:50:51 +00003578 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
Dan Gohman9f8d5712008-07-24 17:57:48 +00003579 (NumElts-1)),
3580 false);
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003581 }
3582 }
3583 }
3584 Out << "}";
3585}
Chris Lattner0452ed62008-03-02 03:57:08 +00003586
Dan Gohman193c2352008-06-02 21:30:49 +00003587void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3588 // Start by copying the entire aggregate value into the result variable.
3589 writeOperand(IVI.getOperand(0));
3590 Out << ";\n ";
3591
3592 // Then do the insert to update the field.
3593 Out << GetValueName(&IVI);
3594 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3595 i != e; ++i) {
3596 const Type *IndexedTy =
3597 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3598 if (isa<ArrayType>(IndexedTy))
3599 Out << ".array[" << *i << "]";
3600 else
3601 Out << ".field" << *i;
3602 }
3603 Out << " = ";
3604 writeOperand(IVI.getOperand(1));
3605}
3606
3607void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3608 Out << "(";
3609 if (isa<UndefValue>(EVI.getOperand(0))) {
3610 Out << "(";
3611 printType(Out, EVI.getType());
3612 Out << ") 0/*UNDEF*/";
3613 } else {
3614 Out << GetValueName(EVI.getOperand(0));
3615 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3616 i != e; ++i) {
3617 const Type *IndexedTy =
3618 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3619 if (isa<ArrayType>(IndexedTy))
3620 Out << ".array[" << *i << "]";
3621 else
3622 Out << ".field" << *i;
3623 }
3624 }
3625 Out << ")";
3626}
3627
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00003628//===----------------------------------------------------------------------===//
3629// External Interface declaration
3630//===----------------------------------------------------------------------===//
3631
Chris Lattner1911fd42006-09-04 04:14:57 +00003632bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
David Greene71847812009-07-14 20:18:05 +00003633 formatted_raw_ostream &o,
Chris Lattner1911fd42006-09-04 04:14:57 +00003634 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00003635 CodeGenOpt::Level OptLevel) {
Chris Lattner0431c962005-06-25 02:48:37 +00003636 if (FileType != TargetMachine::AssemblyFile) return true;
3637
Gordon Henriksence224772008-01-07 01:30:38 +00003638 PM.add(createGCLoweringPass());
Chris Lattnerf7fe4942005-03-03 01:04:50 +00003639 PM.add(createLowerAllocationsPass(true));
Chris Lattner94f4f8e2004-02-13 23:00:29 +00003640 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00003641 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00003642 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00003643 PM.add(new CWriter(o));
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003644 PM.add(createGCInfoDeleter());
Chris Lattnerf31182a2004-02-13 23:18:48 +00003645 return false;
3646}