blob: f292d58b9bd32391a0a2e9cdef622359fcb31ffe [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"
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +000027#include "llvm/ADT/StringExtras.h"
Chris Lattner48130352010-01-13 06:38:18 +000028#include "llvm/ADT/SmallString.h"
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +000029#include "llvm/ADT/STLExtras.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000030#include "llvm/Analysis/ConstantsScanner.h"
Chris Lattnercb3ad012004-05-09 20:41:32 +000031#include "llvm/Analysis/FindUsedTypes.h"
32#include "llvm/Analysis/LoopInfo.h"
Anton Korobeynikove641b522009-08-05 09:29:56 +000033#include "llvm/Analysis/ValueTracking.h"
Gordon Henriksence224772008-01-07 01:30:38 +000034#include "llvm/CodeGen/Passes.h"
Chris Lattner30483732004-06-20 07:49:54 +000035#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner45111d12010-01-16 21:57:06 +000036#include "llvm/Target/Mangler.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattneraf76e592009-08-22 20:48:53 +000038#include "llvm/MC/MCAsmInfo.h"
Chris Lattnera46a3442010-01-13 21:12:34 +000039#include "llvm/MC/MCSymbol.h"
Reid Spencer519e2392007-01-29 17:51:02 +000040#include "llvm/Target/TargetData.h"
Daniel Dunbar51b198a2009-07-15 20:24:03 +000041#include "llvm/Target/TargetRegistry.h"
Chris Lattner23e90702003-11-25 20:49:55 +000042#include "llvm/Support/CallSite.h"
Chris Lattnera05e0ec2004-05-09 03:42:48 +000043#include "llvm/Support/CFG.h"
Torok Edwindac237e2009-07-08 20:53:28 +000044#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000045#include "llvm/Support/FormattedStream.h"
Chris Lattner23e90702003-11-25 20:49:55 +000046#include "llvm/Support/GetElementPtrTypeIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000047#include "llvm/Support/InstVisitor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000048#include "llvm/Support/MathExtras.h"
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +000049#include "llvm/System/Host.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/Config/config.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000051#include <algorithm>
Chris Lattner897bf0d2004-02-13 06:18:21 +000052using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000053
Daniel Dunbar0c795d62009-07-25 06:49:55 +000054extern "C" void LLVMInitializeCBackendTarget() {
55 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000056 RegisterTargetMachine<CTargetMachine> X(TheCBackendTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000057}
Douglas Gregor1555a232009-06-16 20:12:29 +000058
Dan Gohman844731a2008-05-13 00:00:25 +000059namespace {
Chris Lattnerc0dba722010-01-17 18:22:35 +000060 class CBEMCAsmInfo : public MCAsmInfo {
61 public:
Chris Lattner8eeba352010-01-20 06:34:14 +000062 CBEMCAsmInfo() {
Chris Lattnerc0dba722010-01-17 18:22:35 +000063 GlobalPrefix = "";
64 PrivateGlobalPrefix = "";
65 }
66 };
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;
Chris Lattneraf76e592009-08-22 20:48:53 +000097 const MCAsmInfo* 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
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000155 raw_ostream &printType(raw_ostream &Out, const Type *Ty,
David Greene71847812009-07-14 20:18:05 +0000156 bool isSigned = false,
157 const std::string &VariableName = "",
158 bool IgnoreName = false,
159 const AttrListPtr &PAL = AttrListPtr());
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000160 raw_ostream &printSimpleType(raw_ostream &Out, const Type *Ty,
161 bool isSigned,
Owen Andersoncb371882008-08-21 00:14:44 +0000162 const std::string &NameSoFar = "");
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000163
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000164 void printStructReturnPointerFunctionType(raw_ostream &Out,
Devang Patel05988662008-09-25 21:00:45 +0000165 const AttrListPtr &PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +0000166 const PointerType *Ty);
Chris Lattnere05252b42008-03-02 08:07:24 +0000167
168 /// writeOperandDeref - Print the result of dereferencing the specified
169 /// operand with '*'. This is equivalent to printing '*' then using
170 /// writeOperand, but avoids excess syntax in some cases.
171 void writeOperandDeref(Value *Operand) {
172 if (isAddressExposed(Operand)) {
173 // Already something with an address exposed.
174 writeOperandInternal(Operand);
175 } else {
176 Out << "*(";
177 writeOperand(Operand);
178 Out << ")";
179 }
180 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000181
Dan Gohman9f8d5712008-07-24 17:57:48 +0000182 void writeOperand(Value *Operand, bool Static = false);
Chris Lattnere56d9462008-05-31 09:23:55 +0000183 void writeInstComputationInline(Instruction &I);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000184 void writeOperandInternal(Value *Operand, bool Static = false);
Reid Spencer1628cec2006-10-26 06:15:43 +0000185 void writeOperandWithCast(Value* Operand, unsigned Opcode);
Chris Lattner5bda9e42007-09-15 06:51:03 +0000186 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000187 bool writeInstructionCast(const Instruction &I);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000188
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +0000189 void writeMemoryAccess(Value *Operand, const Type *OperandType,
190 bool IsVolatile, unsigned Alignment);
191
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000192 private :
Andrew Lenharthe0cf0752006-11-28 19:53:36 +0000193 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
194
Chris Lattnerc2421432004-05-09 04:30:20 +0000195 void lowerIntrinsics(Function &F);
Chris Lattner4ef51372004-02-14 00:31:10 +0000196
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000197 void printModule(Module *M);
Reid Spencer78d033e2007-01-06 07:24:44 +0000198 void printModuleTypes(const TypeSymbolTable &ST);
Dan Gohman193c2352008-06-02 21:30:49 +0000199 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
Chris Lattner68758072004-05-09 06:20:51 +0000200 void printFloatingPointConstants(Function &F);
Chris Lattneraecc22a2008-10-22 04:53:16 +0000201 void printFloatingPointConstants(const Constant *C);
Chris Lattner4cda8352002-08-20 16:55:48 +0000202 void printFunctionSignature(const Function *F, bool Prototype);
203
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000204 void printFunction(Function &);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000205 void printBasicBlock(BasicBlock *BB);
206 void printLoop(Loop *L);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000207
Reid Spencer3da59db2006-11-27 01:05:10 +0000208 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000209 void printConstant(Constant *CPV, bool Static);
Reid Spencer1628cec2006-10-26 06:15:43 +0000210 void printConstantWithCast(Constant *CPV, unsigned Opcode);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000211 bool printConstExprCast(const ConstantExpr *CE, bool Static);
212 void printConstantArray(ConstantArray *CPA, bool Static);
213 void printConstantVector(ConstantVector *CV, bool Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000214
Chris Lattnere05252b42008-03-02 08:07:24 +0000215 /// isAddressExposed - Return true if the specified value's name needs to
216 /// have its address taken in order to get a C value of the correct type.
217 /// This happens for global variables, byval parameters, and direct allocas.
218 bool isAddressExposed(const Value *V) const {
219 if (const Argument *A = dyn_cast<Argument>(V))
220 return ByValParams.count(A);
221 return isa<GlobalVariable>(V) || isDirectAlloca(V);
222 }
223
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000224 // isInlinableInst - Attempt to inline instructions into their uses to build
225 // trees as much as possible. To do this, we have to consistently decide
226 // what is acceptable to inline, so that variable declarations don't get
227 // printed and an extra copy of the expr is not emitted.
228 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000229 static bool isInlinableInst(const Instruction &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000230 // Always inline cmp instructions, even if they are shared by multiple
Chris Lattner433e25a2004-05-20 20:25:50 +0000231 // expressions. GCC generates horrible code if we don't.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000232 if (isa<CmpInst>(I))
233 return true;
Chris Lattner433e25a2004-05-20 20:25:50 +0000234
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000235 // Must be an expression, must be used exactly once. If it is dead, we
236 // emit it inline where it would go.
Owen Anderson1d0be152009-08-13 21:58:54 +0000237 if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
Misha Brukmand6a29a52005-04-20 16:05:03 +0000238 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Dan Gohman193c2352008-06-02 21:30:49 +0000239 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
240 isa<InsertValueInst>(I))
Chris Lattnerd4e8d312003-07-23 20:45:31 +0000241 // Don't inline a load across a store or other bad things!
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000242 return false;
243
Chris Lattnerb1855ad2008-03-02 05:41:07 +0000244 // Must not be used in inline asm, extractelement, or shufflevector.
245 if (I.hasOneUse()) {
246 const Instruction &User = cast<Instruction>(*I.use_back());
247 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
248 isa<ShuffleVectorInst>(User))
249 return false;
250 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000251
Reid Spencer555a0b12006-12-11 20:39:15 +0000252 // Only inline instruction it if it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000253 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000254 }
255
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000256 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
257 // variables which are accessed with the & operator. This causes GCC to
258 // generate significantly better code than to emit alloca calls directly.
259 //
260 static const AllocaInst *isDirectAlloca(const Value *V) {
261 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
262 if (!AI) return false;
263 if (AI->isArrayAllocation())
264 return 0; // FIXME: we can also inline fixed size array allocas!
Chris Lattner02a3be02003-09-20 14:39:18 +0000265 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000266 return 0;
267 return AI;
268 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000269
270 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
271 static bool isInlineAsm(const Instruction& I) {
272 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
273 return true;
274 return false;
275 }
276
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000277 // Instruction visitation functions
278 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000279
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000280 void visitReturnInst(ReturnInst &I);
281 void visitBranchInst(BranchInst &I);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000282 void visitSwitchInst(SwitchInst &I);
Chris Lattnerab21db72009-10-28 00:19:10 +0000283 void visitIndirectBrInst(IndirectBrInst &I);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000284 void visitInvokeInst(InvokeInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000285 llvm_unreachable("Lowerinvoke pass didn't work!");
Chris Lattnercb3ad012004-05-09 20:41:32 +0000286 }
287
288 void visitUnwindInst(UnwindInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000289 llvm_unreachable("Lowerinvoke pass didn't work!");
Chris Lattnercb3ad012004-05-09 20:41:32 +0000290 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000291 void visitUnreachableInst(UnreachableInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000292
Chris Lattner84e66652003-05-03 07:11:00 +0000293 void visitPHINode(PHINode &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000294 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000295 void visitICmpInst(ICmpInst &I);
296 void visitFCmpInst(FCmpInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000297
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000298 void visitCastInst (CastInst &I);
Chris Lattner9f24a072004-03-12 05:52:14 +0000299 void visitSelectInst(SelectInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000300 void visitCallInst (CallInst &I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000301 void visitInlineAsm(CallInst &I);
Chris Lattner2299fec2008-03-02 08:29:41 +0000302 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000303
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000304 void visitAllocaInst(AllocaInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000305 void visitLoadInst (LoadInst &I);
306 void visitStoreInst (StoreInst &I);
307 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner4d45bd02003-10-18 05:57:43 +0000308 void visitVAArgInst (VAArgInst &I);
Chris Lattner33a44d92008-03-02 03:52:39 +0000309
310 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner0452ed62008-03-02 03:57:08 +0000311 void visitExtractElementInst(ExtractElementInst &I);
Chris Lattnerb1855ad2008-03-02 05:41:07 +0000312 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000313
Dan Gohman193c2352008-06-02 21:30:49 +0000314 void visitInsertValueInst(InsertValueInst &I);
315 void visitExtractValueInst(ExtractValueInst &I);
316
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000317 void visitInstruction(Instruction &I) {
Torok Edwindac237e2009-07-08 20:53:28 +0000318#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000319 errs() << "C Writer does not know about " << I;
Torok Edwindac237e2009-07-08 20:53:28 +0000320#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000321 llvm_unreachable(0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000322 }
323
324 void outputLValue(Instruction *I) {
Bill Wendling145aad02007-02-23 22:45:08 +0000325 Out << " " << GetValueName(I) << " = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000326 }
Chris Lattnercb3ad012004-05-09 20:41:32 +0000327
328 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
John Criswell57bbfce2004-10-20 14:38:39 +0000329 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
330 BasicBlock *Successor, unsigned Indent);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000331 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
332 unsigned Indent);
Chris Lattnere05252b42008-03-02 08:07:24 +0000333 void printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohman9f8d5712008-07-24 17:57:48 +0000334 gep_type_iterator E, bool Static);
Bill Wendling145aad02007-02-23 22:45:08 +0000335
336 std::string GetValueName(const Value *Operand);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000337 };
Chris Lattner4ef51372004-02-14 00:31:10 +0000338}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000339
Devang Patel19974732007-05-03 01:11:54 +0000340char CWriter::ID = 0;
Devang Patel794fd752007-05-01 21:15:47 +0000341
Chris Lattner471f1e92010-01-13 19:54:07 +0000342
Chris Lattner7481ae62010-01-22 18:33:00 +0000343static std::string CBEMangle(const std::string &S) {
Chris Lattner0bd58b02010-01-17 19:32:29 +0000344 std::string Result;
345
346 for (unsigned i = 0, e = S.size(); i != e; ++i)
347 if (isalnum(S[i]) || S[i] == '_') {
348 Result += S[i];
349 } else {
350 Result += '_';
351 Result += 'A'+(S[i]&15);
352 Result += 'A'+((S[i]>>4)&15);
353 Result += '_';
354 }
355 return Result;
Chris Lattner471f1e92010-01-13 19:54:07 +0000356}
357
358
Chris Lattner68758072004-05-09 06:20:51 +0000359/// This method inserts names for any unnamed structure types that are used by
360/// the program, and removes names from structure types that are not used by the
361/// program.
362///
Chris Lattnerf9a05322006-02-13 22:22:42 +0000363bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
Chris Lattner68758072004-05-09 06:20:51 +0000364 // Get a set of types that are used by the program...
365 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000366
Chris Lattner68758072004-05-09 06:20:51 +0000367 // Loop over the module symbol table, removing types from UT that are
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000368 // already named, and removing names for types that are not used.
Chris Lattner68758072004-05-09 06:20:51 +0000369 //
Reid Spencer78d033e2007-01-06 07:24:44 +0000370 TypeSymbolTable &TST = M.getTypeSymbolTable();
371 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
Reid Spencer9231ac82004-05-25 08:53:40 +0000372 TI != TE; ) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000373 TypeSymbolTable::iterator I = TI++;
Chris Lattner19e8b0c2007-01-16 07:22:23 +0000374
Dan Gohman193c2352008-06-02 21:30:49 +0000375 // If this isn't a struct or array type, remove it from our set of types
376 // to name. This simplifies emission later.
Duncan Sands47c51882010-02-16 14:50:09 +0000377 if (!I->second->isStructTy() && !I->second->isOpaqueTy() &&
Duncan Sands1df98592010-02-16 11:11:14 +0000378 !I->second->isArrayTy()) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000379 TST.remove(I);
Chris Lattner19e8b0c2007-01-16 07:22:23 +0000380 } else {
381 // If this is not used, remove it from the symbol table.
382 std::set<const Type *>::iterator UTI = UT.find(I->second);
383 if (UTI == UT.end())
384 TST.remove(I);
385 else
386 UT.erase(UTI); // Only keep one name for this type.
387 }
Reid Spencer9231ac82004-05-25 08:53:40 +0000388 }
Chris Lattner68758072004-05-09 06:20:51 +0000389
390 // UT now contains types that are not named. Loop over it, naming
391 // structure types.
392 //
393 bool Changed = false;
Chris Lattner9d1af972004-05-28 05:47:27 +0000394 unsigned RenameCounter = 0;
Chris Lattner68758072004-05-09 06:20:51 +0000395 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
396 I != E; ++I)
Duncan Sands1df98592010-02-16 11:11:14 +0000397 if ((*I)->isStructTy() || (*I)->isArrayTy()) {
Dan Gohman193c2352008-06-02 21:30:49 +0000398 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
Chris Lattner9d1af972004-05-28 05:47:27 +0000399 ++RenameCounter;
Chris Lattner68758072004-05-09 06:20:51 +0000400 Changed = true;
401 }
Chris Lattnerf9a05322006-02-13 22:22:42 +0000402
403
404 // Loop over all external functions and globals. If we have two with
405 // identical names, merge them.
406 // FIXME: This code should disappear when we don't allow values with the same
407 // names when they have different types!
408 std::map<std::string, GlobalValue*> ExtSymbols;
409 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
410 Function *GV = I++;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000411 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerf9a05322006-02-13 22:22:42 +0000412 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
413 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
414 if (!X.second) {
415 // Found a conflict, replace this global with the previous one.
416 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000417 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000418 GV->eraseFromParent();
419 Changed = true;
420 }
421 }
422 }
423 // Do the same for globals.
424 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
425 I != E;) {
426 GlobalVariable *GV = I++;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000427 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerf9a05322006-02-13 22:22:42 +0000428 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
429 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
430 if (!X.second) {
431 // Found a conflict, replace this global with the previous one.
432 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000433 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000434 GV->eraseFromParent();
435 Changed = true;
436 }
437 }
438 }
439
Chris Lattner68758072004-05-09 06:20:51 +0000440 return Changed;
441}
442
Chris Lattner0c54d892006-05-23 23:39:48 +0000443/// printStructReturnPointerFunctionType - This is like printType for a struct
444/// return type, except, instead of printing the type as void (*)(Struct*, ...)
445/// print it as "Struct (*)(...)", for struct return functions.
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000446void CWriter::printStructReturnPointerFunctionType(raw_ostream &Out,
Devang Patel05988662008-09-25 21:00:45 +0000447 const AttrListPtr &PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +0000448 const PointerType *TheTy) {
449 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000450 std::string tstr;
451 raw_string_ostream FunctionInnards(tstr);
Chris Lattner0c54d892006-05-23 23:39:48 +0000452 FunctionInnards << " (*) (";
453 bool PrintedType = false;
454
455 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
456 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
Reid Spencer0ae96932007-01-07 03:24:48 +0000457 unsigned Idx = 1;
Evan Cheng681d2b82008-01-11 03:07:46 +0000458 for (++I, ++Idx; I != E; ++I, ++Idx) {
Chris Lattner0c54d892006-05-23 23:39:48 +0000459 if (PrintedType)
460 FunctionInnards << ", ";
Evan Cheng681d2b82008-01-11 03:07:46 +0000461 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000462 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Duncan Sands1df98592010-02-16 11:11:14 +0000463 assert(ArgTy->isPointerTy());
Evan Cheng588c6f82008-01-11 09:12:49 +0000464 ArgTy = cast<PointerType>(ArgTy)->getElementType();
465 }
Evan Cheng681d2b82008-01-11 03:07:46 +0000466 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000467 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Chris Lattner0c54d892006-05-23 23:39:48 +0000468 PrintedType = true;
469 }
470 if (FTy->isVarArg()) {
471 if (PrintedType)
472 FunctionInnards << ", ...";
473 } else if (!PrintedType) {
474 FunctionInnards << "void";
475 }
476 FunctionInnards << ')';
Reid Spencer0ae96932007-01-07 03:24:48 +0000477 printType(Out, RetTy,
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000478 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), FunctionInnards.str());
Chris Lattner0c54d892006-05-23 23:39:48 +0000479}
480
Owen Andersoncb371882008-08-21 00:14:44 +0000481raw_ostream &
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000482CWriter::printSimpleType(raw_ostream &Out, const Type *Ty, bool isSigned,
Chris Lattner90683ab2008-03-02 03:41:23 +0000483 const std::string &NameSoFar) {
Duncan Sands1df98592010-02-16 11:11:14 +0000484 assert((Ty->isPrimitiveType() || Ty->isIntegerTy() || Ty->isVectorTy()) &&
Reid Spencera54b7cb2007-01-12 07:05:14 +0000485 "Invalid type for printSimpleType");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000486 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000487 case Type::VoidTyID: return Out << "void " << NameSoFar;
488 case Type::IntegerTyID: {
489 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
490 if (NumBits == 1)
491 return Out << "bool " << NameSoFar;
492 else if (NumBits <= 8)
493 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
494 else if (NumBits <= 16)
495 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
496 else if (NumBits <= 32)
497 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
Dan Gohmand7614802008-04-02 19:40:14 +0000498 else if (NumBits <= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000499 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
Dan Gohmand7614802008-04-02 19:40:14 +0000500 else {
501 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
502 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000503 }
504 }
505 case Type::FloatTyID: return Out << "float " << NameSoFar;
506 case Type::DoubleTyID: return Out << "double " << NameSoFar;
Dale Johannesen53f0bc12007-09-17 00:38:27 +0000507 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
508 // present matches host 'long double'.
509 case Type::X86_FP80TyID:
510 case Type::PPC_FP128TyID:
511 case Type::FP128TyID: return Out << "long double " << NameSoFar;
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000512
513 case Type::VectorTyID: {
514 const VectorType *VTy = cast<VectorType>(Ty);
Chris Lattner90683ab2008-03-02 03:41:23 +0000515 return printSimpleType(Out, VTy->getElementType(), isSigned,
Chris Lattner32cba8e2008-03-02 03:39:43 +0000516 " __attribute__((vector_size(" +
Duncan Sands777d2302009-05-09 07:06:46 +0000517 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000518 }
519
520 default:
Torok Edwindac237e2009-07-08 20:53:28 +0000521#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000522 errs() << "Unknown primitive type: " << *Ty << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +0000523#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000524 llvm_unreachable(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000525 }
526}
Chris Lattner68758072004-05-09 06:20:51 +0000527
Chris Lattner83c57752002-08-19 22:17:53 +0000528// Pass the Type* and the variable name and this prints out the variable
529// declaration.
530//
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000531raw_ostream &CWriter::printType(raw_ostream &Out, const Type *Ty,
David Greene71847812009-07-14 20:18:05 +0000532 bool isSigned, const std::string &NameSoFar,
533 bool IgnoreName, const AttrListPtr &PAL) {
Duncan Sands1df98592010-02-16 11:11:14 +0000534 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || Ty->isVectorTy()) {
Owen Andersoncb371882008-08-21 00:14:44 +0000535 printSimpleType(Out, Ty, isSigned, NameSoFar);
536 return Out;
537 }
538
539 // Check to see if the type is named.
Duncan Sands47c51882010-02-16 14:50:09 +0000540 if (!IgnoreName || Ty->isOpaqueTy()) {
Owen Andersoncb371882008-08-21 00:14:44 +0000541 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
542 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
543 }
544
545 switch (Ty->getTypeID()) {
546 case Type::FunctionTyID: {
547 const FunctionType *FTy = cast<FunctionType>(Ty);
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000548 std::string tstr;
549 raw_string_ostream FunctionInnards(tstr);
Owen Andersoncb371882008-08-21 00:14:44 +0000550 FunctionInnards << " (" << NameSoFar << ") (";
551 unsigned Idx = 1;
552 for (FunctionType::param_iterator I = FTy->param_begin(),
553 E = FTy->param_end(); I != E; ++I) {
554 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000555 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Duncan Sands1df98592010-02-16 11:11:14 +0000556 assert(ArgTy->isPointerTy());
Owen Andersoncb371882008-08-21 00:14:44 +0000557 ArgTy = cast<PointerType>(ArgTy)->getElementType();
558 }
559 if (I != FTy->param_begin())
560 FunctionInnards << ", ";
561 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000562 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Owen Andersoncb371882008-08-21 00:14:44 +0000563 ++Idx;
564 }
565 if (FTy->isVarArg()) {
566 if (FTy->getNumParams())
567 FunctionInnards << ", ...";
568 } else if (!FTy->getNumParams()) {
569 FunctionInnards << "void";
570 }
571 FunctionInnards << ')';
Owen Andersoncb371882008-08-21 00:14:44 +0000572 printType(Out, FTy->getReturnType(),
Duncan Sandsbb1d4512010-02-21 19:15:19 +0000573 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), FunctionInnards.str());
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000574 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000575 }
576 case Type::StructTyID: {
577 const StructType *STy = cast<StructType>(Ty);
578 Out << NameSoFar + " {\n";
579 unsigned Idx = 0;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000580 for (StructType::element_iterator I = STy->element_begin(),
581 E = STy->element_end(); I != E; ++I) {
Chris Lattner83c57752002-08-19 22:17:53 +0000582 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +0000583 printType(Out, *I, false, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000584 Out << ";\n";
585 }
Lauro Ramos Venancioa126bb72007-07-11 19:56:53 +0000586 Out << '}';
587 if (STy->isPacked())
588 Out << " __attribute__ ((packed))";
589 return Out;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000590 }
Chris Lattner83c57752002-08-19 22:17:53 +0000591
592 case Type::PointerTyID: {
593 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000594 std::string ptrName = "*" + NameSoFar;
595
Duncan Sands1df98592010-02-16 11:11:14 +0000596 if (PTy->getElementType()->isArrayTy() ||
597 PTy->getElementType()->isVectorTy())
Chris Lattner8917d362003-11-03 04:31:54 +0000598 ptrName = "(" + ptrName + ")";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000599
Chris Lattner58d74912008-03-12 17:45:29 +0000600 if (!PAL.isEmpty())
Evan Cheng7723ab32008-01-12 18:53:07 +0000601 // Must be a function ptr cast!
602 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
Reid Spencer251f2142007-01-09 17:09:09 +0000603 return printType(Out, PTy->getElementType(), false, ptrName);
Misha Brukman8f9f9a22003-07-21 16:34:35 +0000604 }
Chris Lattner83c57752002-08-19 22:17:53 +0000605
606 case Type::ArrayTyID: {
607 const ArrayType *ATy = cast<ArrayType>(Ty);
608 unsigned NumElements = ATy->getNumElements();
Chris Lattner3e3b6f72004-12-15 23:13:15 +0000609 if (NumElements == 0) NumElements = 1;
Dan Gohman193c2352008-06-02 21:30:49 +0000610 // Arrays are wrapped in structs to allow them to have normal
611 // value semantics (avoiding the array "decay").
612 Out << NameSoFar << " { ";
613 printType(Out, ATy->getElementType(), false,
614 "array[" + utostr(NumElements) + "]");
615 return Out << "; }";
Chris Lattner83c57752002-08-19 22:17:53 +0000616 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000617
618 case Type::OpaqueTyID: {
Owen Anderson52132bf2009-06-26 19:48:37 +0000619 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Chris Lattner04b72c82002-10-16 00:08:22 +0000620 assert(TypeNames.find(Ty) == TypeNames.end());
621 TypeNames[Ty] = TyName;
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000622 return Out << TyName << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000623 }
Chris Lattner83c57752002-08-19 22:17:53 +0000624 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000625 llvm_unreachable("Unhandled case in getTypeProps!");
Chris Lattner83c57752002-08-19 22:17:53 +0000626 }
627
628 return Out;
629}
630
Dan Gohman9f8d5712008-07-24 17:57:48 +0000631void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
Chris Lattner6d492922002-08-19 21:32:41 +0000632
633 // As a special case, print the array as a string if it is an array of
634 // ubytes or an array of sbytes with positive values.
Misha Brukmand6a29a52005-04-20 16:05:03 +0000635 //
Chris Lattner6d492922002-08-19 21:32:41 +0000636 const Type *ETy = CPA->getType()->getElementType();
Owen Anderson1d0be152009-08-13 21:58:54 +0000637 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
638 ETy == Type::getInt8Ty(CPA->getContext()));
Chris Lattner6d492922002-08-19 21:32:41 +0000639
640 // Make sure the last character is a null char, as automatically added by C
Chris Lattner02da6c02003-06-16 12:09:09 +0000641 if (isString && (CPA->getNumOperands() == 0 ||
642 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattner6d492922002-08-19 21:32:41 +0000643 isString = false;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000644
Chris Lattner6d492922002-08-19 21:32:41 +0000645 if (isString) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000646 Out << '\"';
Chris Lattner02da6c02003-06-16 12:09:09 +0000647 // Keep track of whether the last number was a hexadecimal escape
648 bool LastWasHex = false;
649
Chris Lattner6d492922002-08-19 21:32:41 +0000650 // Do not include the last character, which we know is null
651 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000652 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000653
Chris Lattner02da6c02003-06-16 12:09:09 +0000654 // Print it out literally if it is a printable character. The only thing
655 // to be careful about is when the last letter output was a hex escape
656 // code, in which case we have to be careful not to print out hex digits
Chris Lattnerda920902003-06-16 12:21:19 +0000657 // explicitly (the C compiler thinks it is a continuation of the previous
658 // character, sheesh...)
Chris Lattner02da6c02003-06-16 12:09:09 +0000659 //
660 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
661 LastWasHex = false;
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000662 if (C == '"' || C == '\\')
Chris Lattner1f0f37a2008-08-21 05:51:43 +0000663 Out << "\\" << (char)C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000664 else
Chris Lattner1f0f37a2008-08-21 05:51:43 +0000665 Out << (char)C;
Chris Lattner6d492922002-08-19 21:32:41 +0000666 } else {
Chris Lattner02da6c02003-06-16 12:09:09 +0000667 LastWasHex = false;
Chris Lattner6d492922002-08-19 21:32:41 +0000668 switch (C) {
669 case '\n': Out << "\\n"; break;
670 case '\t': Out << "\\t"; break;
671 case '\r': Out << "\\r"; break;
672 case '\v': Out << "\\v"; break;
673 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000674 case '\"': Out << "\\\""; break;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000675 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000676 default:
677 Out << "\\x";
Chris Lattner02da6c02003-06-16 12:09:09 +0000678 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
679 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
680 LastWasHex = true;
Chris Lattner6d492922002-08-19 21:32:41 +0000681 break;
682 }
683 }
684 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000685 Out << '\"';
Chris Lattner6d492922002-08-19 21:32:41 +0000686 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000687 Out << '{';
Chris Lattner6d492922002-08-19 21:32:41 +0000688 if (CPA->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000689 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000690 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000691 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
692 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +0000693 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000694 }
695 }
696 Out << " }";
697 }
698}
699
Dan Gohman9f8d5712008-07-24 17:57:48 +0000700void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
Robert Bocchinob78e8382006-01-20 20:43:57 +0000701 Out << '{';
702 if (CP->getNumOperands()) {
703 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000704 printConstant(cast<Constant>(CP->getOperand(0)), Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000705 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
706 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +0000707 printConstant(cast<Constant>(CP->getOperand(i)), Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000708 }
709 }
710 Out << " }";
711}
712
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000713// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
714// textually as a double (rather than as a reference to a stack-allocated
715// variable). We decide this by converting CFP to a string and back into a
716// double, and then checking whether the conversion results in a bit-equal
717// double to the original value of CFP. This depends on us and the target C
718// compiler agreeing on the conversion process (which is pretty likely since we
719// only deal in IEEE FP).
720//
Chris Lattnercb3ad012004-05-09 20:41:32 +0000721static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Dale Johannesen23a98552008-10-09 23:00:39 +0000722 bool ignored;
Dale Johannesen53f0bc12007-09-17 00:38:27 +0000723 // Do long doubles in hex for now.
Owen Anderson1d0be152009-08-13 21:58:54 +0000724 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
725 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000726 return false;
Dale Johannesen43421b32007-09-06 18:13:44 +0000727 APFloat APF = APFloat(CFP->getValueAPF()); // copy
Owen Anderson1d0be152009-08-13 21:58:54 +0000728 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
Dale Johannesen23a98552008-10-09 23:00:39 +0000729 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Reid Spencerbcf81242006-11-05 19:26:37 +0000730#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000731 char Buffer[100];
Dale Johannesen43421b32007-09-06 18:13:44 +0000732 sprintf(Buffer, "%a", APF.convertToDouble());
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000733 if (!strncmp(Buffer, "0x", 2) ||
734 !strncmp(Buffer, "-0x", 3) ||
735 !strncmp(Buffer, "+0x", 3))
Dale Johannesen43421b32007-09-06 18:13:44 +0000736 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000737 return false;
738#else
Dale Johannesen43421b32007-09-06 18:13:44 +0000739 std::string StrVal = ftostr(APF);
Chris Lattner9860e772003-10-12 04:36:29 +0000740
741 while (StrVal[0] == ' ')
742 StrVal.erase(StrVal.begin());
743
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000744 // Check to make sure that the stringized number is not some string like "Inf"
745 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaekeb471a232003-06-17 23:55:35 +0000746 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
747 ((StrVal[0] == '-' || StrVal[0] == '+') &&
748 (StrVal[1] >= '0' && StrVal[1] <= '9')))
749 // Reparse stringized version!
Dale Johannesen43421b32007-09-06 18:13:44 +0000750 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
Brian Gaekeb471a232003-06-17 23:55:35 +0000751 return false;
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000752#endif
Brian Gaekeb471a232003-06-17 23:55:35 +0000753}
Chris Lattner6d492922002-08-19 21:32:41 +0000754
Reid Spencer3da59db2006-11-27 01:05:10 +0000755/// Print out the casting for a cast operation. This does the double casting
756/// necessary for conversion to the destination type, if necessary.
Reid Spencer3da59db2006-11-27 01:05:10 +0000757/// @brief Print a cast
758void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000759 // Print the destination type cast
760 switch (opc) {
761 case Instruction::UIToFP:
762 case Instruction::SIToFP:
763 case Instruction::IntToPtr:
764 case Instruction::Trunc:
765 case Instruction::BitCast:
766 case Instruction::FPExt:
767 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
768 Out << '(';
769 printType(Out, DstTy);
770 Out << ')';
771 break;
772 case Instruction::ZExt:
773 case Instruction::PtrToInt:
774 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
775 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000776 printSimpleType(Out, DstTy, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000777 Out << ')';
778 break;
779 case Instruction::SExt:
780 case Instruction::FPToSI: // For these, make sure we get a signed dest
781 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000782 printSimpleType(Out, DstTy, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000783 Out << ')';
784 break;
785 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000786 llvm_unreachable("Invalid cast opcode");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000787 }
788
789 // Print the source type cast
Reid Spencer3da59db2006-11-27 01:05:10 +0000790 switch (opc) {
791 case Instruction::UIToFP:
792 case Instruction::ZExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000793 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000794 printSimpleType(Out, SrcTy, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000795 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000796 break;
797 case Instruction::SIToFP:
798 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000799 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000800 printSimpleType(Out, SrcTy, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000801 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000802 break;
803 case Instruction::IntToPtr:
804 case Instruction::PtrToInt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000805 // Avoid "cast to pointer from integer of different size" warnings
806 Out << "(unsigned long)";
807 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000808 case Instruction::Trunc:
809 case Instruction::BitCast:
810 case Instruction::FPExt:
811 case Instruction::FPTrunc:
812 case Instruction::FPToSI:
813 case Instruction::FPToUI:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000814 break; // These don't need a source cast.
Reid Spencer3da59db2006-11-27 01:05:10 +0000815 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000816 llvm_unreachable("Invalid cast opcode");
Reid Spencer3da59db2006-11-27 01:05:10 +0000817 break;
818 }
819}
820
Chris Lattner6d492922002-08-19 21:32:41 +0000821// printConstant - The LLVM Constant to C Constant converter.
Dan Gohman9f8d5712008-07-24 17:57:48 +0000822void CWriter::printConstant(Constant *CPV, bool Static) {
Chris Lattner6d492922002-08-19 21:32:41 +0000823 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
824 switch (CE->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000825 case Instruction::Trunc:
826 case Instruction::ZExt:
827 case Instruction::SExt:
828 case Instruction::FPTrunc:
829 case Instruction::FPExt:
830 case Instruction::UIToFP:
831 case Instruction::SIToFP:
832 case Instruction::FPToUI:
833 case Instruction::FPToSI:
834 case Instruction::PtrToInt:
835 case Instruction::IntToPtr:
836 case Instruction::BitCast:
837 Out << "(";
838 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
Chris Lattner72623362007-05-03 02:57:13 +0000839 if (CE->getOpcode() == Instruction::SExt &&
Owen Anderson1d0be152009-08-13 21:58:54 +0000840 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
Reid Spencercee7ba32007-05-02 02:17:41 +0000841 // Make sure we really sext from bool here by subtracting from 0
842 Out << "0-";
Reid Spencercee7ba32007-05-02 02:17:41 +0000843 }
Dan Gohman9f8d5712008-07-24 17:57:48 +0000844 printConstant(CE->getOperand(0), Static);
Owen Anderson1d0be152009-08-13 21:58:54 +0000845 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
Chris Lattner72623362007-05-03 02:57:13 +0000846 (CE->getOpcode() == Instruction::Trunc ||
847 CE->getOpcode() == Instruction::FPToUI ||
848 CE->getOpcode() == Instruction::FPToSI ||
849 CE->getOpcode() == Instruction::PtrToInt)) {
850 // Make sure we really truncate to bool here by anding with 1
851 Out << "&1u";
852 }
853 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000854 return;
Chris Lattner72623362007-05-03 02:57:13 +0000855
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000856 case Instruction::GetElementPtr:
Chris Lattnere05252b42008-03-02 08:07:24 +0000857 Out << "(";
858 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
Dan Gohman9f8d5712008-07-24 17:57:48 +0000859 gep_type_end(CPV), Static);
Chris Lattnere05252b42008-03-02 08:07:24 +0000860 Out << ")";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000861 return;
Chris Lattner6683dbf2004-04-01 05:28:26 +0000862 case Instruction::Select:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000863 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000864 printConstant(CE->getOperand(0), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000865 Out << '?';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000866 printConstant(CE->getOperand(1), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000867 Out << ':';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000868 printConstant(CE->getOperand(2), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000869 Out << ')';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000870 return;
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000871 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000872 case Instruction::FAdd:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000873 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000874 case Instruction::FSub:
Chris Lattner29255922003-08-14 19:19:53 +0000875 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000876 case Instruction::FMul:
Reid Spencer1628cec2006-10-26 06:15:43 +0000877 case Instruction::SDiv:
878 case Instruction::UDiv:
879 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +0000880 case Instruction::URem:
881 case Instruction::SRem:
882 case Instruction::FRem:
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000883 case Instruction::And:
884 case Instruction::Or:
885 case Instruction::Xor:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000886 case Instruction::ICmp:
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000887 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000888 case Instruction::LShr:
889 case Instruction::AShr:
Reid Spencer72ddc212006-10-26 06:17:40 +0000890 {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000891 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000892 bool NeedsClosingParens = printConstExprCast(CE, Static);
Reid Spencer1628cec2006-10-26 06:15:43 +0000893 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
Chris Lattner29255922003-08-14 19:19:53 +0000894 switch (CE->getOpcode()) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000895 case Instruction::Add:
896 case Instruction::FAdd: Out << " + "; break;
897 case Instruction::Sub:
898 case Instruction::FSub: Out << " - "; break;
899 case Instruction::Mul:
900 case Instruction::FMul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +0000901 case Instruction::URem:
902 case Instruction::SRem:
903 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000904 case Instruction::UDiv:
905 case Instruction::SDiv:
906 case Instruction::FDiv: Out << " / "; break;
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000907 case Instruction::And: Out << " & "; break;
908 case Instruction::Or: Out << " | "; break;
909 case Instruction::Xor: Out << " ^ "; break;
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000910 case Instruction::Shl: Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000911 case Instruction::LShr:
912 case Instruction::AShr: Out << " >> "; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000913 case Instruction::ICmp:
914 switch (CE->getPredicate()) {
915 case ICmpInst::ICMP_EQ: Out << " == "; break;
916 case ICmpInst::ICMP_NE: Out << " != "; break;
917 case ICmpInst::ICMP_SLT:
918 case ICmpInst::ICMP_ULT: Out << " < "; break;
919 case ICmpInst::ICMP_SLE:
920 case ICmpInst::ICMP_ULE: Out << " <= "; break;
921 case ICmpInst::ICMP_SGT:
922 case ICmpInst::ICMP_UGT: Out << " > "; break;
923 case ICmpInst::ICMP_SGE:
924 case ICmpInst::ICMP_UGE: Out << " >= "; break;
Torok Edwinc23197a2009-07-14 16:55:14 +0000925 default: llvm_unreachable("Illegal ICmp predicate");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000926 }
927 break;
Torok Edwinc23197a2009-07-14 16:55:14 +0000928 default: llvm_unreachable("Illegal opcode here!");
Chris Lattner29255922003-08-14 19:19:53 +0000929 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000930 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
931 if (NeedsClosingParens)
932 Out << "))";
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000933 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000934 return;
Reid Spencer72ddc212006-10-26 06:17:40 +0000935 }
Reid Spencerb801a272007-01-08 06:58:32 +0000936 case Instruction::FCmp: {
937 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000938 bool NeedsClosingParens = printConstExprCast(CE, Static);
Reid Spencerb801a272007-01-08 06:58:32 +0000939 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
940 Out << "0";
941 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
942 Out << "1";
943 else {
944 const char* op = 0;
945 switch (CE->getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000946 default: llvm_unreachable("Illegal FCmp predicate");
Reid Spencerb801a272007-01-08 06:58:32 +0000947 case FCmpInst::FCMP_ORD: op = "ord"; break;
948 case FCmpInst::FCMP_UNO: op = "uno"; break;
949 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
950 case FCmpInst::FCMP_UNE: op = "une"; break;
951 case FCmpInst::FCMP_ULT: op = "ult"; break;
952 case FCmpInst::FCMP_ULE: op = "ule"; break;
953 case FCmpInst::FCMP_UGT: op = "ugt"; break;
954 case FCmpInst::FCMP_UGE: op = "uge"; break;
955 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
956 case FCmpInst::FCMP_ONE: op = "one"; break;
957 case FCmpInst::FCMP_OLT: op = "olt"; break;
958 case FCmpInst::FCMP_OLE: op = "ole"; break;
959 case FCmpInst::FCMP_OGT: op = "ogt"; break;
960 case FCmpInst::FCMP_OGE: op = "oge"; break;
961 }
962 Out << "llvm_fcmp_" << op << "(";
963 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
964 Out << ", ";
965 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
966 Out << ")";
967 }
968 if (NeedsClosingParens)
969 Out << "))";
970 Out << ')';
Anton Korobeynikovdceadaf2007-12-21 23:33:44 +0000971 return;
Reid Spencerb801a272007-01-08 06:58:32 +0000972 }
Chris Lattner6d492922002-08-19 21:32:41 +0000973 default:
Torok Edwindac237e2009-07-08 20:53:28 +0000974#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000975 errs() << "CWriter Error: Unhandled constant expression: "
Bill Wendlingf5da1332006-12-07 22:21:48 +0000976 << *CE << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +0000977#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000978 llvm_unreachable(0);
Chris Lattner6d492922002-08-19 21:32:41 +0000979 }
Dan Gohman17dab192008-05-23 16:57:00 +0000980 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
Chris Lattner665825e2004-10-17 17:48:59 +0000981 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +0000982 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnerd9a706e2008-03-02 08:14:45 +0000983 Out << ")/*UNDEF*/";
Duncan Sands1df98592010-02-16 11:11:14 +0000984 if (!CPV->getType()->isVectorTy()) {
Chris Lattnerd9a706e2008-03-02 08:14:45 +0000985 Out << "0)";
986 } else {
987 Out << "{})";
988 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000989 return;
Chris Lattner6d492922002-08-19 21:32:41 +0000990 }
991
Reid Spencerfbe7ae92007-01-08 08:00:00 +0000992 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
993 const Type* Ty = CI->getType();
Owen Anderson1d0be152009-08-13 21:58:54 +0000994 if (Ty == Type::getInt1Ty(CPV->getContext()))
Chris Lattnerc8b6d332008-03-02 03:16:38 +0000995 Out << (CI->getZExtValue() ? '1' : '0');
Owen Anderson1d0be152009-08-13 21:58:54 +0000996 else if (Ty == Type::getInt32Ty(CPV->getContext()))
Chris Lattnerc8b6d332008-03-02 03:16:38 +0000997 Out << CI->getZExtValue() << 'u';
998 else if (Ty->getPrimitiveSizeInBits() > 32)
999 Out << CI->getZExtValue() << "ull";
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001000 else {
1001 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001002 printSimpleType(Out, Ty, false) << ')';
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001003 if (CI->isMinValue(true))
1004 Out << CI->getZExtValue() << 'u';
1005 else
1006 Out << CI->getSExtValue();
Dale Johannesenf4786cc2009-05-19 00:46:42 +00001007 Out << ')';
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001008 }
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001009 return;
1010 }
1011
1012 switch (CPV->getType()->getTypeID()) {
Chris Lattner6d492922002-08-19 21:32:41 +00001013 case Type::FloatTyID:
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001014 case Type::DoubleTyID:
1015 case Type::X86_FP80TyID:
1016 case Type::PPC_FP128TyID:
1017 case Type::FP128TyID: {
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001018 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattneredd8ce12003-05-03 03:14:35 +00001019 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001020 if (I != FPConstantMap.end()) {
1021 // Because of FP precision problems we must load from a stack allocated
1022 // value that holds the value in hex.
Owen Anderson1d0be152009-08-13 21:58:54 +00001023 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
1024 "float" :
1025 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
1026 "double" :
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001027 "long double")
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001028 << "*)&FPConstant" << I->second << ')';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001029 } else {
Chris Lattnerabec4742008-10-17 06:11:48 +00001030 double V;
Owen Anderson1d0be152009-08-13 21:58:54 +00001031 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
Chris Lattnerabec4742008-10-17 06:11:48 +00001032 V = FPC->getValueAPF().convertToFloat();
Owen Anderson1d0be152009-08-13 21:58:54 +00001033 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
Chris Lattnerabec4742008-10-17 06:11:48 +00001034 V = FPC->getValueAPF().convertToDouble();
1035 else {
1036 // Long double. Convert the number to double, discarding precision.
1037 // This is not awesome, but it at least makes the CBE output somewhat
1038 // useful.
1039 APFloat Tmp = FPC->getValueAPF();
1040 bool LosesInfo;
1041 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1042 V = Tmp.convertToDouble();
1043 }
1044
Dale Johannesen43421b32007-09-06 18:13:44 +00001045 if (IsNAN(V)) {
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001046 // The value is NaN
Misha Brukmand6a29a52005-04-20 16:05:03 +00001047
Dale Johannesen43421b32007-09-06 18:13:44 +00001048 // FIXME the actual NaN bits should be emitted.
Brian Gaeke8a702e82004-08-25 19:00:42 +00001049 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1050 // it's 0x7ff4.
1051 const unsigned long QuietNaN = 0x7ff8UL;
Reid Spencer3ed469c2006-11-02 20:25:50 +00001052 //const unsigned long SignalNaN = 0x7ff4UL;
Brian Gaeke8a702e82004-08-25 19:00:42 +00001053
1054 // We need to grab the first part of the FP #
Brian Gaeke8a702e82004-08-25 19:00:42 +00001055 char Buffer[100];
1056
Dale Johannesen43421b32007-09-06 18:13:44 +00001057 uint64_t ll = DoubleToBits(V);
Reid Spencer2bc320d2006-05-31 22:26:11 +00001058 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
Brian Gaeke8a702e82004-08-25 19:00:42 +00001059
1060 std::string Num(&Buffer[0], &Buffer[6]);
1061 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1062
Owen Anderson1d0be152009-08-13 21:58:54 +00001063 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
Brian Gaeke8a702e82004-08-25 19:00:42 +00001064 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1065 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001066 else
Brian Gaeke8a702e82004-08-25 19:00:42 +00001067 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1068 << Buffer << "\") /*nan*/ ";
Dale Johannesen43421b32007-09-06 18:13:44 +00001069 } else if (IsInf(V)) {
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001070 // The value is Inf
Dale Johannesen43421b32007-09-06 18:13:44 +00001071 if (V < 0) Out << '-';
Owen Anderson1d0be152009-08-13 21:58:54 +00001072 Out << "LLVM_INF" <<
1073 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
Brian Gaeke8a702e82004-08-25 19:00:42 +00001074 << " /*inf*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001075 } else {
Brian Gaeke07b52b32004-08-25 19:37:26 +00001076 std::string Num;
Reid Spencerbcf81242006-11-05 19:26:37 +00001077#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Brian Gaeke07b52b32004-08-25 19:37:26 +00001078 // Print out the constant as a floating point number.
1079 char Buffer[100];
Dale Johannesen43421b32007-09-06 18:13:44 +00001080 sprintf(Buffer, "%a", V);
Brian Gaeke07b52b32004-08-25 19:37:26 +00001081 Num = Buffer;
1082#else
Dale Johannesen43421b32007-09-06 18:13:44 +00001083 Num = ftostr(FPC->getValueAPF());
Brian Gaeke07b52b32004-08-25 19:37:26 +00001084#endif
Dale Johannesen43421b32007-09-06 18:13:44 +00001085 Out << Num;
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001086 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001087 }
1088 break;
1089 }
Chris Lattner6d492922002-08-19 21:32:41 +00001090
1091 case Type::ArrayTyID:
Dan Gohman1a245392008-07-23 18:41:03 +00001092 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001093 if (!Static) {
1094 Out << "(";
1095 printType(Out, CPV->getType());
1096 Out << ")";
1097 }
Dan Gohman193c2352008-06-02 21:30:49 +00001098 Out << "{ "; // Arrays are wrapped in struct types.
Chris Lattner939732a2008-03-02 05:46:57 +00001099 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001100 printConstantArray(CA, Static);
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001101 } else {
1102 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001103 const ArrayType *AT = cast<ArrayType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001104 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001105 if (AT->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001106 Out << ' ';
Owen Andersona7235ea2009-07-31 20:28:14 +00001107 Constant *CZ = Constant::getNullValue(AT->getElementType());
Dan Gohman9f8d5712008-07-24 17:57:48 +00001108 printConstant(CZ, Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001109 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1110 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001111 printConstant(CZ, Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001112 }
1113 }
1114 Out << " }";
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001115 }
Dan Gohman193c2352008-06-02 21:30:49 +00001116 Out << " }"; // Arrays are wrapped in struct types.
Chris Lattner6d492922002-08-19 21:32:41 +00001117 break;
1118
Reid Spencer9d6565a2007-02-15 02:26:10 +00001119 case Type::VectorTyID:
Chris Lattner85feab62008-03-02 03:29:50 +00001120 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001121 if (!Static) {
1122 Out << "(";
1123 printType(Out, CPV->getType());
1124 Out << ")";
1125 }
Chris Lattner939732a2008-03-02 05:46:57 +00001126 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001127 printConstantVector(CV, Static);
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001128 } else {
1129 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1130 const VectorType *VT = cast<VectorType>(CPV->getType());
1131 Out << "{ ";
Owen Andersona7235ea2009-07-31 20:28:14 +00001132 Constant *CZ = Constant::getNullValue(VT->getElementType());
Dan Gohman9f8d5712008-07-24 17:57:48 +00001133 printConstant(CZ, Static);
Chris Lattner0a3d4d92008-03-02 03:18:46 +00001134 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001135 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001136 printConstant(CZ, Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +00001137 }
1138 Out << " }";
Robert Bocchinob78e8382006-01-20 20:43:57 +00001139 }
1140 break;
1141
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001142 case Type::StructTyID:
Dan Gohman1a245392008-07-23 18:41:03 +00001143 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001144 if (!Static) {
1145 Out << "(";
1146 printType(Out, CPV->getType());
1147 Out << ")";
1148 }
Chris Lattnera9d12c02004-10-16 18:12:13 +00001149 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001150 const StructType *ST = cast<StructType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001151 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001152 if (ST->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001153 Out << ' ';
Owen Andersona7235ea2009-07-31 20:28:14 +00001154 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001155 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1156 Out << ", ";
Owen Andersona7235ea2009-07-31 20:28:14 +00001157 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001158 }
Chris Lattner6d492922002-08-19 21:32:41 +00001159 }
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001160 Out << " }";
1161 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001162 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001163 if (CPV->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001164 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001165 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001166 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1167 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001168 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001169 }
1170 }
1171 Out << " }";
Chris Lattner6d492922002-08-19 21:32:41 +00001172 }
Chris Lattner6d492922002-08-19 21:32:41 +00001173 break;
Chris Lattner6d492922002-08-19 21:32:41 +00001174
1175 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001176 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattnercf135cb2003-06-02 03:10:53 +00001177 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +00001178 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnercf135cb2003-06-02 03:10:53 +00001179 Out << ")/*NULL*/0)";
Chris Lattner6d492922002-08-19 21:32:41 +00001180 break;
Reid Spencer518310c2004-07-18 00:44:37 +00001181 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001182 writeOperand(GV, Static);
Chris Lattner6d492922002-08-19 21:32:41 +00001183 break;
1184 }
1185 // FALL THROUGH
1186 default:
Torok Edwindac237e2009-07-08 20:53:28 +00001187#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001188 errs() << "Unknown constant type: " << *CPV << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +00001189#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001190 llvm_unreachable(0);
Chris Lattner6d492922002-08-19 21:32:41 +00001191 }
1192}
1193
Reid Spencer1628cec2006-10-26 06:15:43 +00001194// Some constant expressions need to be casted back to the original types
1195// because their operands were casted to the expected type. This function takes
1196// care of detecting that case and printing the cast for the ConstantExpr.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001197bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001198 bool NeedsExplicitCast = false;
Reid Spencer3da59db2006-11-27 01:05:10 +00001199 const Type *Ty = CE->getOperand(0)->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001200 bool TypeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001201 switch (CE->getOpcode()) {
Dan Gohman5a11aba2008-07-18 18:43:12 +00001202 case Instruction::Add:
1203 case Instruction::Sub:
1204 case Instruction::Mul:
1205 // We need to cast integer arithmetic so that it is always performed
1206 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001207 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001208 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001209 case Instruction::UDiv: NeedsExplicitCast = true; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001210 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001211 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001212 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
Reid Spencer3da59db2006-11-27 01:05:10 +00001213 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001214 Ty = CE->getType();
1215 NeedsExplicitCast = true;
1216 TypeIsSigned = true;
1217 break;
1218 case Instruction::ZExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00001219 case Instruction::Trunc:
1220 case Instruction::FPTrunc:
1221 case Instruction::FPExt:
1222 case Instruction::UIToFP:
1223 case Instruction::SIToFP:
1224 case Instruction::FPToUI:
1225 case Instruction::FPToSI:
1226 case Instruction::PtrToInt:
1227 case Instruction::IntToPtr:
1228 case Instruction::BitCast:
1229 Ty = CE->getType();
1230 NeedsExplicitCast = true;
1231 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001232 default: break;
1233 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001234 if (NeedsExplicitCast) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001235 Out << "((";
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001236 if (Ty->isIntegerTy() && Ty != Type::getInt1Ty(Ty->getContext()))
Reid Spencera54b7cb2007-01-12 07:05:14 +00001237 printSimpleType(Out, Ty, TypeIsSigned);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001238 else
Reid Spencer251f2142007-01-09 17:09:09 +00001239 printType(Out, Ty); // not integer, sign doesn't matter
Reid Spencer1628cec2006-10-26 06:15:43 +00001240 Out << ")(";
1241 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001242 return NeedsExplicitCast;
Reid Spencer1628cec2006-10-26 06:15:43 +00001243}
1244
1245// Print a constant assuming that it is the operand for a given Opcode. The
1246// opcodes that care about sign need to cast their operands to the expected
1247// type before the operation proceeds. This function does the casting.
1248void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1249
1250 // Extract the operand's type, we'll need it.
1251 const Type* OpTy = CPV->getType();
1252
1253 // Indicate whether to do the cast or not.
1254 bool shouldCast = false;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001255 bool typeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001256
1257 // Based on the Opcode for which this Constant is being written, determine
1258 // the new type to which the operand should be casted by setting the value
Reid Spencer3da59db2006-11-27 01:05:10 +00001259 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1260 // casted below.
Reid Spencer1628cec2006-10-26 06:15:43 +00001261 switch (Opcode) {
1262 default:
1263 // for most instructions, it doesn't matter
1264 break;
Dan Gohman5a11aba2008-07-18 18:43:12 +00001265 case Instruction::Add:
1266 case Instruction::Sub:
1267 case Instruction::Mul:
1268 // We need to cast integer arithmetic so that it is always performed
1269 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001270 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001271 case Instruction::UDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001272 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001273 shouldCast = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001274 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001275 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001276 case Instruction::SDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001277 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001278 shouldCast = true;
1279 typeIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001280 break;
1281 }
1282
Reid Spencer3da59db2006-11-27 01:05:10 +00001283 // Write out the casted constant if we should, otherwise just write the
Reid Spencer1628cec2006-10-26 06:15:43 +00001284 // operand.
1285 if (shouldCast) {
1286 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001287 printSimpleType(Out, OpTy, typeIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001288 Out << ")";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001289 printConstant(CPV, false);
Reid Spencer1628cec2006-10-26 06:15:43 +00001290 Out << ")";
1291 } else
Dan Gohman9f8d5712008-07-24 17:57:48 +00001292 printConstant(CPV, false);
Reid Spencer1628cec2006-10-26 06:15:43 +00001293}
1294
Bill Wendling145aad02007-02-23 22:45:08 +00001295std::string CWriter::GetValueName(const Value *Operand) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001296 // Mangle globals with the standard mangler interface for LLC compatibility.
Chris Lattner471f1e92010-01-13 19:54:07 +00001297 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand)) {
1298 SmallString<128> Str;
1299 Mang->getNameWithPrefix(Str, GV, false);
Chris Lattner7481ae62010-01-22 18:33:00 +00001300 return CBEMangle(Str.str().str());
Chris Lattner471f1e92010-01-13 19:54:07 +00001301 }
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001302
1303 std::string Name = Operand->getName();
1304
1305 if (Name.empty()) { // Assign unique names to local temporaries.
1306 unsigned &No = AnonValueNumbers[Operand];
1307 if (No == 0)
1308 No = ++NextAnonValueNumber;
1309 Name = "tmp__" + utostr(No);
1310 }
1311
1312 std::string VarName;
1313 VarName.reserve(Name.capacity());
Bill Wendling145aad02007-02-23 22:45:08 +00001314
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001315 for (std::string::iterator I = Name.begin(), E = Name.end();
1316 I != E; ++I) {
1317 char ch = *I;
Bill Wendling145aad02007-02-23 22:45:08 +00001318
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001319 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1320 (ch >= '0' && ch <= '9') || ch == '_')) {
1321 char buffer[5];
1322 sprintf(buffer, "_%x_", ch);
1323 VarName += buffer;
1324 } else
1325 VarName += ch;
Bill Wendling145aad02007-02-23 22:45:08 +00001326 }
1327
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001328 return "llvm_cbe_" + VarName;
Bill Wendling145aad02007-02-23 22:45:08 +00001329}
1330
Chris Lattnere56d9462008-05-31 09:23:55 +00001331/// writeInstComputationInline - Emit the computation for the specified
1332/// instruction inline, with no destination provided.
1333void CWriter::writeInstComputationInline(Instruction &I) {
Dale Johannesen06398942009-06-18 01:07:23 +00001334 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1335 // Validate this.
1336 const Type *Ty = I.getType();
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001337 if (Ty->isIntegerTy() && (Ty!=Type::getInt1Ty(I.getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001338 Ty!=Type::getInt8Ty(I.getContext()) &&
1339 Ty!=Type::getInt16Ty(I.getContext()) &&
1340 Ty!=Type::getInt32Ty(I.getContext()) &&
1341 Ty!=Type::getInt64Ty(I.getContext()))) {
Torok Edwindac237e2009-07-08 20:53:28 +00001342 llvm_report_error("The C backend does not currently support integer "
1343 "types of widths other than 1, 8, 16, 32, 64.\n"
1344 "This is being tracked as PR 4158.");
Dale Johannesen06398942009-06-18 01:07:23 +00001345 }
1346
Chris Lattnere56d9462008-05-31 09:23:55 +00001347 // If this is a non-trivial bool computation, make sure to truncate down to
1348 // a 1 bit value. This is important because we want "add i1 x, y" to return
1349 // "0" when x and y are true, not "2" for example.
1350 bool NeedBoolTrunc = false;
Owen Anderson1d0be152009-08-13 21:58:54 +00001351 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1352 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
Chris Lattnere56d9462008-05-31 09:23:55 +00001353 NeedBoolTrunc = true;
1354
1355 if (NeedBoolTrunc)
1356 Out << "((";
1357
1358 visit(I);
1359
1360 if (NeedBoolTrunc)
1361 Out << ")&1)";
1362}
1363
1364
Dan Gohman9f8d5712008-07-24 17:57:48 +00001365void CWriter::writeOperandInternal(Value *Operand, bool Static) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001366 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnere56d9462008-05-31 09:23:55 +00001367 // Should we inline this instruction to build a tree?
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001368 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001369 Out << '(';
Chris Lattnere56d9462008-05-31 09:23:55 +00001370 writeInstComputationInline(*I);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001371 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001372 return;
1373 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001374
Reid Spencer518310c2004-07-18 00:44:37 +00001375 Constant* CPV = dyn_cast<Constant>(Operand);
Bill Wendling145aad02007-02-23 22:45:08 +00001376
1377 if (CPV && !isa<GlobalValue>(CPV))
Dan Gohman9f8d5712008-07-24 17:57:48 +00001378 printConstant(CPV, Static);
Bill Wendling145aad02007-02-23 22:45:08 +00001379 else
1380 Out << GetValueName(Operand);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001381}
1382
Dan Gohman9f8d5712008-07-24 17:57:48 +00001383void CWriter::writeOperand(Value *Operand, bool Static) {
Chris Lattnere05252b42008-03-02 08:07:24 +00001384 bool isAddressImplicit = isAddressExposed(Operand);
1385 if (isAddressImplicit)
Reid Spencer3da59db2006-11-27 01:05:10 +00001386 Out << "(&"; // Global variables are referenced as their addresses by llvm
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001387
Dan Gohman9f8d5712008-07-24 17:57:48 +00001388 writeOperandInternal(Operand, Static);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001389
Chris Lattnere05252b42008-03-02 08:07:24 +00001390 if (isAddressImplicit)
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001391 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001392}
1393
Reid Spencer1628cec2006-10-26 06:15:43 +00001394// Some instructions need to have their result value casted back to the
1395// original types because their operands were casted to the expected type.
1396// This function takes care of detecting that case and printing the cast
1397// for the Instruction.
1398bool CWriter::writeInstructionCast(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001399 const Type *Ty = I.getOperand(0)->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00001400 switch (I.getOpcode()) {
Dan Gohman5a11aba2008-07-18 18:43:12 +00001401 case Instruction::Add:
1402 case Instruction::Sub:
1403 case Instruction::Mul:
1404 // We need to cast integer arithmetic so that it is always performed
1405 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001406 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001407 case Instruction::URem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001408 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001409 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001410 printSimpleType(Out, Ty, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001411 Out << ")(";
1412 return true;
Reid Spencer3822ff52006-11-08 06:47:33 +00001413 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001414 case Instruction::SRem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001415 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001416 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001417 printSimpleType(Out, Ty, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001418 Out << ")(";
1419 return true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001420 default: break;
1421 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001422 return false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001423}
1424
1425// Write the operand with a cast to another type based on the Opcode being used.
1426// This will be used in cases where an instruction has specific type
1427// requirements (usually signedness) for its operands.
1428void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1429
1430 // Extract the operand's type, we'll need it.
1431 const Type* OpTy = Operand->getType();
1432
1433 // Indicate whether to do the cast or not.
1434 bool shouldCast = false;
1435
Reid Spencere4d87aa2006-12-23 06:05:41 +00001436 // Indicate whether the cast should be to a signed type or not.
1437 bool castIsSigned = false;
1438
Reid Spencer1628cec2006-10-26 06:15:43 +00001439 // Based on the Opcode for which this Operand is being written, determine
1440 // the new type to which the operand should be casted by setting the value
1441 // of OpTy. If we change OpTy, also set shouldCast to true.
1442 switch (Opcode) {
1443 default:
1444 // for most instructions, it doesn't matter
1445 break;
Dan Gohman5a11aba2008-07-18 18:43:12 +00001446 case Instruction::Add:
1447 case Instruction::Sub:
1448 case Instruction::Mul:
1449 // We need to cast integer arithmetic so that it is always performed
1450 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001451 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001452 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001453 case Instruction::URem: // Cast to unsigned first
1454 shouldCast = true;
1455 castIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001456 break;
Chris Lattner96b207c2007-09-22 20:16:48 +00001457 case Instruction::GetElementPtr:
Reid Spencer3822ff52006-11-08 06:47:33 +00001458 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001459 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001460 case Instruction::SRem: // Cast to signed first
1461 shouldCast = true;
1462 castIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001463 break;
1464 }
1465
1466 // Write out the casted operand if we should, otherwise just write the
1467 // operand.
1468 if (shouldCast) {
1469 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001470 printSimpleType(Out, OpTy, castIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001471 Out << ")";
Chris Lattner72623362007-05-03 02:57:13 +00001472 writeOperand(Operand);
Reid Spencer1628cec2006-10-26 06:15:43 +00001473 Out << ")";
1474 } else
1475 writeOperand(Operand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001476}
Reid Spencer1628cec2006-10-26 06:15:43 +00001477
Reid Spencere4d87aa2006-12-23 06:05:41 +00001478// Write the operand with a cast to another type based on the icmp predicate
1479// being used.
Chris Lattner5bda9e42007-09-15 06:51:03 +00001480void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1481 // This has to do a cast to ensure the operand has the right signedness.
1482 // Also, if the operand is a pointer, we make sure to cast to an integer when
1483 // doing the comparison both for signedness and so that the C compiler doesn't
1484 // optimize things like "p < NULL" to false (p may contain an integer value
1485 // f.e.).
1486 bool shouldCast = Cmp.isRelational();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001487
1488 // Write out the casted operand if we should, otherwise just write the
1489 // operand.
Chris Lattner5bda9e42007-09-15 06:51:03 +00001490 if (!shouldCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001491 writeOperand(Operand);
Chris Lattner5bda9e42007-09-15 06:51:03 +00001492 return;
1493 }
1494
1495 // Should this be a signed comparison? If so, convert to signed.
Nick Lewycky4a134af2009-10-25 05:20:17 +00001496 bool castIsSigned = Cmp.isSigned();
Chris Lattner5bda9e42007-09-15 06:51:03 +00001497
1498 // If the operand was a pointer, convert to a large integer type.
1499 const Type* OpTy = Operand->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00001500 if (OpTy->isPointerTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001501 OpTy = TD->getIntPtrType(Operand->getContext());
Chris Lattner5bda9e42007-09-15 06:51:03 +00001502
1503 Out << "((";
1504 printSimpleType(Out, OpTy, castIsSigned);
1505 Out << ")";
1506 writeOperand(Operand);
1507 Out << ")";
Reid Spencer1628cec2006-10-26 06:15:43 +00001508}
1509
Chris Lattner41488192003-06-28 17:15:12 +00001510// generateCompilerSpecificCode - This is where we add conditional compilation
1511// directives to cater to specific compilers as need be.
1512//
David Greene71847812009-07-14 20:18:05 +00001513static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
Dan Gohman271515a2008-04-02 23:52:49 +00001514 const TargetData *TD) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001515 // Alloca is hard to get, and we don't want to include stdlib.h here.
Chris Lattner41488192003-06-28 17:15:12 +00001516 Out << "/* get a declaration for alloca */\n"
Chris Lattnerd9477602006-06-02 18:54:01 +00001517 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
Anton Korobeynikov57fc00d2007-04-17 09:20:00 +00001518 << "#define alloca(x) __builtin_alloca((x))\n"
Anton Korobeynikove392c832009-08-05 09:31:07 +00001519 << "#define _alloca(x) __builtin_alloca((x))\n"
Reid Spencera8411a62005-01-23 04:32:47 +00001520 << "#elif defined(__APPLE__)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001521 << "extern void *__builtin_alloca(unsigned long);\n"
1522 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001523 << "#define longjmp _longjmp\n"
1524 << "#define setjmp _setjmp\n"
Brian Gaekece630052004-12-10 05:44:45 +00001525 << "#elif defined(__sun__)\n"
1526 << "#if defined(__sparcv9)\n"
1527 << "extern void *__builtin_alloca(unsigned long);\n"
1528 << "#else\n"
1529 << "extern void *__builtin_alloca(unsigned int);\n"
1530 << "#endif\n"
1531 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikove392c832009-08-05 09:31:07 +00001532 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
Chris Lattner60e66742004-10-06 04:21:52 +00001533 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohenab478952007-03-28 23:08:37 +00001534 << "#elif defined(_MSC_VER)\n"
Jeff Cohene2cd2a02007-03-29 17:42:21 +00001535 << "#define inline _inline\n"
Jeff Cohenab478952007-03-28 23:08:37 +00001536 << "#define alloca(x) _alloca(x)\n"
1537 << "#else\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001538 << "#include <alloca.h>\n"
1539 << "#endif\n\n";
Chris Lattner41488192003-06-28 17:15:12 +00001540
1541 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1542 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner9bda5f52003-06-28 17:53:05 +00001543 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattner41488192003-06-28 17:15:12 +00001544 << "#define __attribute__(X)\n"
Brian Gaeke27f7a712003-12-11 00:24:36 +00001545 << "#endif\n\n";
1546
Brian Gaeke27f7a712003-12-11 00:24:36 +00001547 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1548 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1549 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1550 << "#elif defined(__GNUC__)\n"
1551 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1552 << "#else\n"
1553 << "#define __EXTERNAL_WEAK__\n"
1554 << "#endif\n\n";
Brian Gaeke27f7a712003-12-11 00:24:36 +00001555
1556 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1557 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1558 << "#define __ATTRIBUTE_WEAK__\n"
1559 << "#elif defined(__GNUC__)\n"
1560 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1561 << "#else\n"
1562 << "#define __ATTRIBUTE_WEAK__\n"
1563 << "#endif\n\n";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001564
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001565 // Add hidden visibility support. FIXME: APPLE_CC?
1566 Out << "#if defined(__GNUC__)\n"
1567 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1568 << "#endif\n\n";
1569
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001570 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1571 // From the GCC documentation:
Misha Brukmand6a29a52005-04-20 16:05:03 +00001572 //
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001573 // double __builtin_nan (const char *str)
1574 //
1575 // This is an implementation of the ISO C99 function nan.
1576 //
1577 // Since ISO C99 defines this function in terms of strtod, which we do
1578 // not implement, a description of the parsing is in order. The string is
1579 // parsed as by strtol; that is, the base is recognized by leading 0 or
1580 // 0x prefixes. The number parsed is placed in the significand such that
1581 // the least significant bit of the number is at the least significant
1582 // bit of the significand. The number is truncated to fit the significand
1583 // field provided. The significand is forced to be a quiet NaN.
1584 //
1585 // This function, if given a string literal, is evaluated early enough
1586 // that it is considered a compile-time constant.
1587 //
1588 // float __builtin_nanf (const char *str)
1589 //
1590 // Similar to __builtin_nan, except the return type is float.
1591 //
1592 // double __builtin_inf (void)
1593 //
1594 // Similar to __builtin_huge_val, except a warning is generated if the
1595 // target floating-point format does not support infinities. This
1596 // function is suitable for implementing the ISO C99 macro INFINITY.
1597 //
1598 // float __builtin_inff (void)
1599 //
1600 // Similar to __builtin_inf, except the return type is float.
1601 Out << "#ifdef __GNUC__\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001602 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1603 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1604 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1605 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1606 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1607 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
Chris Lattnerf9a05322006-02-13 22:22:42 +00001608 << "#define LLVM_PREFETCH(addr,rw,locality) "
1609 "__builtin_prefetch(addr,rw,locality)\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001610 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1611 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001612 << "#define LLVM_ASM __asm__\n"
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001613 << "#else\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001614 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1615 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1616 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1617 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1618 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1619 << "#define LLVM_INFF 0.0F /* Float */\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001620 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001621 << "#define __ATTRIBUTE_CTOR__\n"
1622 << "#define __ATTRIBUTE_DTOR__\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001623 << "#define LLVM_ASM(X)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001624 << "#endif\n\n";
Chris Lattner40c1b662007-05-13 22:19:27 +00001625
1626 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1627 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1628 << "#define __builtin_stack_restore(X) /* noop */\n"
1629 << "#endif\n\n";
Chris Lattner50a8a172005-05-06 06:58:42 +00001630
Dan Gohman271515a2008-04-02 23:52:49 +00001631 // Output typedefs for 128-bit integers. If these are needed with a
1632 // 32-bit target or with a C compiler that doesn't support mode(TI),
1633 // more drastic measures will be needed.
Chris Lattner9e4ff942008-06-16 04:25:29 +00001634 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1635 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1636 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1637 << "#endif\n\n";
Dan Gohmand7614802008-04-02 19:40:14 +00001638
Chris Lattner50a8a172005-05-06 06:58:42 +00001639 // Output target-specific code that should be inserted into main.
1640 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001641}
1642
Chris Lattner9a571ba2006-03-07 22:58:23 +00001643/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1644/// the StaticTors set.
1645static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1646 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1647 if (!InitList) return;
1648
1649 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1650 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1651 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1652
1653 if (CS->getOperand(1)->isNullValue())
1654 return; // Found a null terminator, exit printing.
1655 Constant *FP = CS->getOperand(1);
1656 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +00001657 if (CE->isCast())
Chris Lattner9a571ba2006-03-07 22:58:23 +00001658 FP = CE->getOperand(0);
1659 if (Function *F = dyn_cast<Function>(FP))
1660 StaticTors.insert(F);
1661 }
1662}
1663
1664enum SpecialGlobalClass {
1665 NotSpecial = 0,
1666 GlobalCtors, GlobalDtors,
1667 NotPrinted
1668};
1669
1670/// getGlobalVariableClass - If this is a global that is specially recognized
1671/// by LLVM, return a code that indicates how we should handle it.
1672static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1673 // If this is a global ctors/dtors list, handle it now.
1674 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1675 if (GV->getName() == "llvm.global_ctors")
1676 return GlobalCtors;
1677 else if (GV->getName() == "llvm.global_dtors")
1678 return GlobalDtors;
1679 }
1680
Dan Gohmanf451cb82010-02-10 16:03:48 +00001681 // Otherwise, if it is other metadata, don't print it. This catches things
Chris Lattner9a571ba2006-03-07 22:58:23 +00001682 // like debug information.
1683 if (GV->getSection() == "llvm.metadata")
1684 return NotPrinted;
1685
1686 return NotSpecial;
1687}
1688
Anton Korobeynikove641b522009-08-05 09:29:56 +00001689// PrintEscapedString - Print each character of the specified string, escaping
1690// it if it is not printable or if it is an escape char.
1691static void PrintEscapedString(const char *Str, unsigned Length,
1692 raw_ostream &Out) {
1693 for (unsigned i = 0; i != Length; ++i) {
1694 unsigned char C = Str[i];
1695 if (isprint(C) && C != '\\' && C != '"')
1696 Out << C;
1697 else if (C == '\\')
1698 Out << "\\\\";
1699 else if (C == '\"')
1700 Out << "\\\"";
1701 else if (C == '\t')
1702 Out << "\\t";
1703 else
1704 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1705 }
1706}
1707
1708// PrintEscapedString - Print each character of the specified string, escaping
1709// it if it is not printable or if it is an escape char.
1710static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1711 PrintEscapedString(Str.c_str(), Str.size(), Out);
1712}
Chris Lattner9a571ba2006-03-07 22:58:23 +00001713
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001714bool CWriter::doInitialization(Module &M) {
Daniel Dunbar53448652009-07-17 03:43:21 +00001715 FunctionPass::doInitialization(M);
1716
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001717 // Initialize
1718 TheModule = &M;
Chris Lattnerc2421432004-05-09 04:30:20 +00001719
Reid Spencer519e2392007-01-29 17:51:02 +00001720 TD = new TargetData(&M);
1721 IL = new IntrinsicLowering(*TD);
1722 IL->AddPrototypes(M);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001723
Chris Lattnerc0dba722010-01-17 18:22:35 +00001724#if 0
1725 std::string Triple = TheModule->getTargetTriple();
1726 if (Triple.empty())
1727 Triple = llvm::sys::getHostTriple();
1728
1729 std::string E;
1730 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
1731 TAsm = Match->createAsmInfo(Triple);
1732#endif
Chris Lattner8eeba352010-01-20 06:34:14 +00001733 TAsm = new CBEMCAsmInfo();
Chris Lattnerc0dba722010-01-17 18:22:35 +00001734 Mang = new Mangler(*TAsm);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001735
Chris Lattner9a571ba2006-03-07 22:58:23 +00001736 // Keep track of which functions are static ctors/dtors so they can have
1737 // an attribute added to their prototypes.
1738 std::set<Function*> StaticCtors, StaticDtors;
1739 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1740 I != E; ++I) {
1741 switch (getGlobalVariableClass(I)) {
1742 default: break;
1743 case GlobalCtors:
1744 FindStaticTors(I, StaticCtors);
1745 break;
1746 case GlobalDtors:
1747 FindStaticTors(I, StaticDtors);
1748 break;
1749 }
1750 }
1751
Chris Lattner16c7bb22002-05-09 02:28:59 +00001752 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001753 Out << "/* Provide Declarations */\n";
Chris Lattnerc59c1182003-11-16 22:06:14 +00001754 Out << "#include <stdarg.h>\n"; // Varargs support
1755 Out << "#include <setjmp.h>\n"; // Unwind support
Dan Gohman271515a2008-04-02 23:52:49 +00001756 generateCompilerSpecificCode(Out, TD);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001757
Chris Lattnercf135cb2003-06-02 03:10:53 +00001758 // Provide a definition for `bool' if not compiling with a C++ compiler.
1759 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +00001760 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001761
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001762 << "\n\n/* Support for floating point constants */\n"
1763 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +00001764 << "typedef unsigned int ConstantFloatTy;\n"
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001765 << "typedef struct { unsigned long long f1; unsigned short f2; "
1766 "unsigned short pad[3]; } ConstantFP80Ty;\n"
Dale Johannesen6e644732007-10-15 01:05:37 +00001767 // This is used for both kinds of 128-bit long double; meaning differs.
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001768 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1769 " ConstantFP128Ty;\n"
Chris Lattnera4d4a852002-08-19 21:48:40 +00001770 << "\n\n/* Global Declarations */\n";
1771
1772 // First output all the declarations for the program, because C requires
1773 // Functions & globals to be declared before they are used.
1774 //
Anton Korobeynikove641b522009-08-05 09:29:56 +00001775 if (!M.getModuleInlineAsm().empty()) {
1776 Out << "/* Module asm statements */\n"
1777 << "asm(";
1778
1779 // Split the string into lines, to make it easier to read the .ll file.
1780 std::string Asm = M.getModuleInlineAsm();
1781 size_t CurPos = 0;
1782 size_t NewLine = Asm.find_first_of('\n', CurPos);
1783 while (NewLine != std::string::npos) {
1784 // We found a newline, print the portion of the asm string from the
1785 // last newline up to this newline.
1786 Out << "\"";
1787 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1788 Out);
1789 Out << "\\n\"\n";
1790 CurPos = NewLine+1;
1791 NewLine = Asm.find_first_of('\n', CurPos);
1792 }
1793 Out << "\"";
1794 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1795 Out << "\");\n"
1796 << "/* End Module asm statements */\n";
1797 }
Chris Lattner16c7bb22002-05-09 02:28:59 +00001798
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001799 // Loop over the symbol table, emitting all named constants...
Reid Spencer78d033e2007-01-06 07:24:44 +00001800 printModuleTypes(M.getTypeSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001801
Chris Lattnera4d4a852002-08-19 21:48:40 +00001802 // Global variable declarations...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001803 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001804 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001805 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1806 I != E; ++I) {
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001807
Dale Johannesenaafce772008-05-14 20:12:51 +00001808 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1809 I->hasCommonLinkage())
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001810 Out << "extern ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001811 else if (I->hasDLLImportLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001812 Out << "__declspec(dllimport) ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001813 else
1814 continue; // Internal Global
1815
1816 // Thread Local Storage
1817 if (I->isThreadLocal())
1818 Out << "__thread ";
1819
1820 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1821
1822 if (I->hasExternalWeakLinkage())
1823 Out << " __EXTERNAL_WEAK__";
1824 Out << ";\n";
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001825 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001826 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001827
Chris Lattnera4d4a852002-08-19 21:48:40 +00001828 // Function declarations
Chris Lattner9a571ba2006-03-07 22:58:23 +00001829 Out << "\n/* Function Declarations */\n";
Chris Lattner57da2522005-08-23 20:22:50 +00001830 Out << "double fmod(double, double);\n"; // Support for FP rem
1831 Out << "float fmodf(float, float);\n";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001832 Out << "long double fmodl(long double, long double);\n";
Evan Cheng3e3aa862008-06-07 07:50:29 +00001833
Chris Lattner9a571ba2006-03-07 22:58:23 +00001834 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1835 // Don't print declarations for intrinsic functions.
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001836 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
Reid Spencer2cb46e12006-10-22 09:58:21 +00001837 I->getName() != "longjmp" && I->getName() != "_setjmp") {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001838 if (I->hasExternalWeakLinkage())
1839 Out << "extern ";
Chris Lattner9a571ba2006-03-07 22:58:23 +00001840 printFunctionSignature(I, true);
Evan Cheng3e3aa862008-06-07 07:50:29 +00001841 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
Chris Lattner9a571ba2006-03-07 22:58:23 +00001842 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001843 if (I->hasExternalWeakLinkage())
1844 Out << " __EXTERNAL_WEAK__";
Chris Lattner9a571ba2006-03-07 22:58:23 +00001845 if (StaticCtors.count(I))
1846 Out << " __ATTRIBUTE_CTOR__";
1847 if (StaticDtors.count(I))
1848 Out << " __ATTRIBUTE_DTOR__";
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001849 if (I->hasHiddenVisibility())
1850 Out << " __HIDDEN__";
Evan Cheng3e3aa862008-06-07 07:50:29 +00001851
1852 if (I->hasName() && I->getName()[0] == 1)
Daniel Dunbar8f603022009-07-22 21:10:12 +00001853 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
Evan Cheng3e3aa862008-06-07 07:50:29 +00001854
Chris Lattner9a571ba2006-03-07 22:58:23 +00001855 Out << ";\n";
Chris Lattner4cda8352002-08-20 16:55:48 +00001856 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001857 }
1858
Joel Stanley54f60322003-06-25 04:52:09 +00001859 // Output the global variable declarations
Chris Lattnere4d5c442005-03-15 04:54:21 +00001860 if (!M.global_empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +00001861 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001862 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1863 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +00001864 if (!I->isDeclaration()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001865 // Ignore special globals, such as debug info.
1866 if (getGlobalVariableClass(I))
1867 continue;
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001868
Rafael Espindolabb46f522009-01-15 20:18:42 +00001869 if (I->hasLocalLinkage())
Chris Lattnercc16a8e2004-12-03 17:19:10 +00001870 Out << "static ";
1871 else
1872 Out << "extern ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001873
1874 // Thread Local Storage
1875 if (I->isThreadLocal())
1876 Out << "__thread ";
1877
Reid Spencer251f2142007-01-09 17:09:09 +00001878 printType(Out, I->getType()->getElementType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00001879 GetValueName(I));
Chris Lattner2580d4f2003-11-03 17:32:38 +00001880
1881 if (I->hasLinkOnceLinkage())
1882 Out << " __attribute__((common))";
Dale Johannesenaafce772008-05-14 20:12:51 +00001883 else if (I->hasCommonLinkage()) // FIXME is this right?
1884 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner2580d4f2003-11-03 17:32:38 +00001885 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001886 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001887 else if (I->hasExternalWeakLinkage())
1888 Out << " __EXTERNAL_WEAK__";
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001889 if (I->hasHiddenVisibility())
1890 Out << " __HIDDEN__";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001891 Out << ";\n";
1892 }
1893 }
1894
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001895 // Output the global variable definitions and contents...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001896 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001897 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Evan Cheng3e3aa862008-06-07 07:50:29 +00001898 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
Chris Lattnerf9a05322006-02-13 22:22:42 +00001899 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +00001900 if (!I->isDeclaration()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001901 // Ignore special globals, such as debug info.
1902 if (getGlobalVariableClass(I))
1903 continue;
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001904
Rafael Espindolabb46f522009-01-15 20:18:42 +00001905 if (I->hasLocalLinkage())
Chris Lattnere8e035b2002-10-16 20:08:47 +00001906 Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001907 else if (I->hasDLLImportLinkage())
1908 Out << "__declspec(dllimport) ";
1909 else if (I->hasDLLExportLinkage())
1910 Out << "__declspec(dllexport) ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001911
1912 // Thread Local Storage
1913 if (I->isThreadLocal())
1914 Out << "__thread ";
1915
Reid Spencer251f2142007-01-09 17:09:09 +00001916 printType(Out, I->getType()->getElementType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00001917 GetValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +00001918 if (I->hasLinkOnceLinkage())
1919 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +00001920 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001921 Out << " __ATTRIBUTE_WEAK__";
Dale Johannesenaafce772008-05-14 20:12:51 +00001922 else if (I->hasCommonLinkage())
1923 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner5ea326a2003-11-03 17:35:00 +00001924
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001925 if (I->hasHiddenVisibility())
1926 Out << " __HIDDEN__";
1927
Chris Lattner5ea326a2003-11-03 17:35:00 +00001928 // If the initializer is not null, emit the initializer. If it is null,
1929 // we try to avoid emitting large amounts of zeros. The problem with
1930 // this, however, occurs when the variable has weak linkage. In this
1931 // case, the assembler will complain about the variable being both weak
1932 // and common, so we disable this optimization.
Dale Johannesenaafce772008-05-14 20:12:51 +00001933 // FIXME common linkage should avoid this problem.
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001934 if (!I->getInitializer()->isNullValue()) {
Chris Lattner940b08d2003-06-06 07:10:24 +00001935 Out << " = " ;
Dan Gohman9f8d5712008-07-24 17:57:48 +00001936 writeOperand(I->getInitializer(), true);
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001937 } else if (I->hasWeakLinkage()) {
1938 // We have to specify an initializer, but it doesn't have to be
1939 // complete. If the value is an aggregate, print out { 0 }, and let
1940 // the compiler figure out the rest of the zeros.
1941 Out << " = " ;
Duncan Sands1df98592010-02-16 11:11:14 +00001942 if (I->getInitializer()->getType()->isStructTy() ||
1943 I->getInitializer()->getType()->isVectorTy()) {
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001944 Out << "{ 0 }";
Duncan Sands1df98592010-02-16 11:11:14 +00001945 } else if (I->getInitializer()->getType()->isArrayTy()) {
Dan Gohman193c2352008-06-02 21:30:49 +00001946 // As with structs and vectors, but with an extra set of braces
1947 // because arrays are wrapped in structs.
1948 Out << "{ { 0 } }";
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001949 } else {
1950 // Just print it out normally.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001951 writeOperand(I->getInitializer(), true);
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001952 }
Chris Lattner940b08d2003-06-06 07:10:24 +00001953 }
Chris Lattnere8e035b2002-10-16 20:08:47 +00001954 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00001955 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001956 }
1957
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001958 if (!M.empty())
Chris Lattnera4d4a852002-08-19 21:48:40 +00001959 Out << "\n\n/* Function Bodies */\n";
Reid Spencerb801a272007-01-08 06:58:32 +00001960
1961 // Emit some helper functions for dealing with FCMP instruction's
1962 // predicates
1963 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
1964 Out << "return X == X && Y == Y; }\n";
1965 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
1966 Out << "return X != X || Y != Y; }\n";
1967 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001968 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00001969 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001970 Out << "return X != Y; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00001971 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001972 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00001973 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001974 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00001975 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001976 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00001977 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001978 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00001979 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001980 Out << "return X == Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00001981 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001982 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00001983 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001984 Out << "return X < Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00001985 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001986 Out << "return X > Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00001987 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001988 Out << "return X <= Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00001989 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001990 Out << "return X >= Y ; }\n";
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001991 return false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001992}
1993
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001994
Chris Lattner9860e772003-10-12 04:36:29 +00001995/// Output all floating point constants that cannot be printed accurately...
Chris Lattner68758072004-05-09 06:20:51 +00001996void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner9860e772003-10-12 04:36:29 +00001997 // Scan the module for floating point constants. If any FP constant is used
1998 // in the function, we want to redirect it here so that we do not depend on
1999 // the precision of the printed form, unless the printed form preserves
2000 // precision.
2001 //
Chris Lattner68758072004-05-09 06:20:51 +00002002 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2003 I != E; ++I)
Chris Lattneraecc22a2008-10-22 04:53:16 +00002004 printFloatingPointConstants(*I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002005
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002006 Out << '\n';
Chris Lattner68758072004-05-09 06:20:51 +00002007}
Chris Lattner9860e772003-10-12 04:36:29 +00002008
Chris Lattneraecc22a2008-10-22 04:53:16 +00002009void CWriter::printFloatingPointConstants(const Constant *C) {
2010 // If this is a constant expression, recursively check for constant fp values.
2011 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2012 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2013 printFloatingPointConstants(CE->getOperand(i));
2014 return;
2015 }
2016
2017 // Otherwise, check for a FP constant that we need to print.
2018 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2019 if (FPC == 0 ||
2020 // Do not put in FPConstantMap if safe.
2021 isFPCSafeToPrint(FPC) ||
2022 // Already printed this constant?
2023 FPConstantMap.count(FPC))
2024 return;
2025
2026 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2027
Owen Anderson1d0be152009-08-13 21:58:54 +00002028 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002029 double Val = FPC->getValueAPF().convertToDouble();
2030 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2031 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2032 << " = 0x" << utohexstr(i)
2033 << "ULL; /* " << Val << " */\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00002034 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002035 float Val = FPC->getValueAPF().convertToFloat();
2036 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2037 getZExtValue();
2038 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2039 << " = 0x" << utohexstr(i)
2040 << "U; /* " << Val << " */\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00002041 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002042 // api needed to prevent premature destruction
2043 APInt api = FPC->getValueAPF().bitcastToAPInt();
2044 const uint64_t *p = api.getRawData();
2045 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002046 << " = { 0x" << utohexstr(p[0])
2047 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
Chris Lattneraecc22a2008-10-22 04:53:16 +00002048 << "}; /* Long double constant */\n";
Anton Korobeynikovefc3f3a2009-08-26 17:39:23 +00002049 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2050 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002051 APInt api = FPC->getValueAPF().bitcastToAPInt();
2052 const uint64_t *p = api.getRawData();
2053 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2054 << " = { 0x"
2055 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2056 << "}; /* Long double constant */\n";
2057
2058 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002059 llvm_unreachable("Unknown float type!");
Chris Lattneraecc22a2008-10-22 04:53:16 +00002060 }
2061}
2062
2063
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002064
Chris Lattner2db41cd2002-09-20 15:12:13 +00002065/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchinob78e8382006-01-20 20:43:57 +00002066/// type name is found, emit its declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +00002067///
Reid Spencer78d033e2007-01-06 07:24:44 +00002068void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
Reid Spencer555a0b12006-12-11 20:39:15 +00002069 Out << "/* Helper union for bitcasts */\n";
2070 Out << "typedef union {\n";
Reid Spencer47857812006-12-31 05:55:36 +00002071 Out << " unsigned int Int32;\n";
2072 Out << " unsigned long long Int64;\n";
Reid Spencer22b36fb2006-12-12 00:11:08 +00002073 Out << " float Float;\n";
2074 Out << " double Double;\n";
Reid Spencer555a0b12006-12-11 20:39:15 +00002075 Out << "} llvmBitCastUnion;\n";
2076
Chris Lattnerb15fde22005-03-06 02:28:23 +00002077 // We are only interested in the type plane of the symbol table.
Reid Spencer78d033e2007-01-06 07:24:44 +00002078 TypeSymbolTable::const_iterator I = TST.begin();
2079 TypeSymbolTable::const_iterator End = TST.end();
Chris Lattnerb15fde22005-03-06 02:28:23 +00002080
2081 // If there are no type names, exit early.
2082 if (I == End) return;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002083
Chris Lattner58d04d42002-09-20 15:18:30 +00002084 // Print out forward declarations for structure types before anything else!
2085 Out << "/* Structure forward decls */\n";
Chris Lattnera80cc932007-01-16 18:02:45 +00002086 for (; I != End; ++I) {
Chris Lattner7481ae62010-01-22 18:33:00 +00002087 std::string Name = "struct " + CBEMangle("l_"+I->first);
Chris Lattner471f1e92010-01-13 19:54:07 +00002088 Out << Name << ";\n";
2089 TypeNames.insert(std::make_pair(I->second, Name));
Chris Lattnera80cc932007-01-16 18:02:45 +00002090 }
Chris Lattner58d04d42002-09-20 15:18:30 +00002091
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002092 Out << '\n';
Chris Lattner58d04d42002-09-20 15:18:30 +00002093
Chris Lattner19e8b0c2007-01-16 07:22:23 +00002094 // Now we can print out typedefs. Above, we guaranteed that this can only be
Chris Lattnera80cc932007-01-16 18:02:45 +00002095 // for struct or opaque types.
Chris Lattner58d04d42002-09-20 15:18:30 +00002096 Out << "/* Typedefs */\n";
Reid Spencer78d033e2007-01-06 07:24:44 +00002097 for (I = TST.begin(); I != End; ++I) {
Chris Lattner7481ae62010-01-22 18:33:00 +00002098 std::string Name = CBEMangle("l_"+I->first);
Chris Lattner68758072004-05-09 06:20:51 +00002099 Out << "typedef ";
Chris Lattner471f1e92010-01-13 19:54:07 +00002100 printType(Out, I->second, false, Name);
Chris Lattner68758072004-05-09 06:20:51 +00002101 Out << ";\n";
2102 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002103
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002104 Out << '\n';
Chris Lattner3ef6dc72002-05-09 14:40:11 +00002105
Chris Lattner2c601a72002-09-20 15:05:40 +00002106 // Keep track of which structures have been printed so far...
Dan Gohman193c2352008-06-02 21:30:49 +00002107 std::set<const Type *> StructPrinted;
Chris Lattner2c601a72002-09-20 15:05:40 +00002108
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002109 // Loop over all structures then push them into the stack so they are
2110 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +00002111 //
Chris Lattner58d04d42002-09-20 15:18:30 +00002112 Out << "/* Structure contents */\n";
Reid Spencer78d033e2007-01-06 07:24:44 +00002113 for (I = TST.begin(); I != End; ++I)
Duncan Sands1df98592010-02-16 11:11:14 +00002114 if (I->second->isStructTy() || I->second->isArrayTy())
Chris Lattnerfa395ec2003-11-02 01:29:27 +00002115 // Only print out used types!
Dan Gohman193c2352008-06-02 21:30:49 +00002116 printContainedStructs(I->second, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002117}
2118
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002119// Push the struct onto the stack and recursively push all structs
2120// this one depends on.
Robert Bocchinob78e8382006-01-20 20:43:57 +00002121//
Reid Spencerac9dcb92007-02-15 03:39:18 +00002122// TODO: Make this work properly with vector types
Robert Bocchinob78e8382006-01-20 20:43:57 +00002123//
Chris Lattner2c601a72002-09-20 15:05:40 +00002124void CWriter::printContainedStructs(const Type *Ty,
Dan Gohman193c2352008-06-02 21:30:49 +00002125 std::set<const Type*> &StructPrinted) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002126 // Don't walk through pointers.
Duncan Sands1df98592010-02-16 11:11:14 +00002127 if (Ty->isPointerTy() || Ty->isPrimitiveType() || Ty->isIntegerTy())
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002128 return;
Chris Lattner14d9b202006-01-20 18:57:03 +00002129
2130 // Print all contained types first.
2131 for (Type::subtype_iterator I = Ty->subtype_begin(),
2132 E = Ty->subtype_end(); I != E; ++I)
2133 printContainedStructs(*I, StructPrinted);
2134
Duncan Sands1df98592010-02-16 11:11:14 +00002135 if (Ty->isStructTy() || Ty->isArrayTy()) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002136 // Check to see if we have already printed this struct.
Dan Gohman193c2352008-06-02 21:30:49 +00002137 if (StructPrinted.insert(Ty).second) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002138 // Print structure type out.
Dan Gohman193c2352008-06-02 21:30:49 +00002139 std::string Name = TypeNames[Ty];
2140 printType(Out, Ty, false, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00002141 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002142 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002143 }
2144}
2145
Chris Lattner4cda8352002-08-20 16:55:48 +00002146void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002147 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002148 bool isStructReturn = F->hasStructRetAttr();
Chris Lattner0c54d892006-05-23 23:39:48 +00002149
Rafael Espindolabb46f522009-01-15 20:18:42 +00002150 if (F->hasLocalLinkage()) Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002151 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2152 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002153 switch (F->getCallingConv()) {
2154 case CallingConv::X86_StdCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002155 Out << "__attribute__((stdcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002156 break;
2157 case CallingConv::X86_FastCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002158 Out << "__attribute__((fastcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002159 break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002160 default:
2161 break;
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002162 }
2163
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002164 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00002165 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Devang Patel05988662008-09-25 21:00:45 +00002166 const AttrListPtr &PAL = F->getAttributes();
Misha Brukmand6a29a52005-04-20 16:05:03 +00002167
Duncan Sandsbb1d4512010-02-21 19:15:19 +00002168 std::string tstr;
2169 raw_string_ostream FunctionInnards(tstr);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002170
Nick Hildenbrandt98502372002-11-18 20:55:50 +00002171 // Print out the name...
Bill Wendling145aad02007-02-23 22:45:08 +00002172 FunctionInnards << GetValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00002173
Chris Lattner0c54d892006-05-23 23:39:48 +00002174 bool PrintedArg = false;
Reid Spencer5cbf9852007-01-30 20:08:39 +00002175 if (!F->isDeclaration()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00002176 if (!F->arg_empty()) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002177 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
Evan Cheng681d2b82008-01-11 03:07:46 +00002178 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +00002179
2180 // If this is a struct-return function, don't print the hidden
2181 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002182 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002183 assert(I != E && "Invalid struct return function!");
2184 ++I;
Evan Cheng681d2b82008-01-11 03:07:46 +00002185 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002186 }
2187
Chris Lattneredd8ce12003-05-03 03:14:35 +00002188 std::string ArgName;
Chris Lattner0c54d892006-05-23 23:39:48 +00002189 for (; I != E; ++I) {
2190 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00002191 if (I->hasName() || !Prototype)
Bill Wendling145aad02007-02-23 22:45:08 +00002192 ArgName = GetValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002193 else
Chris Lattner4cda8352002-08-20 16:55:48 +00002194 ArgName = "";
Evan Cheng681d2b82008-01-11 03:07:46 +00002195 const Type *ArgTy = I->getType();
Devang Patel05988662008-09-25 21:00:45 +00002196 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng588c6f82008-01-11 09:12:49 +00002197 ArgTy = cast<PointerType>(ArgTy)->getElementType();
Chris Lattnere05252b42008-03-02 08:07:24 +00002198 ByValParams.insert(I);
Evan Cheng588c6f82008-01-11 09:12:49 +00002199 }
Evan Cheng681d2b82008-01-11 03:07:46 +00002200 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002201 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002202 ArgName);
Chris Lattner0c54d892006-05-23 23:39:48 +00002203 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002204 ++Idx;
Chris Lattnerdeed7a52002-05-09 15:18:52 +00002205 }
2206 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002207 } else {
Chris Lattner0c54d892006-05-23 23:39:48 +00002208 // Loop over the arguments, printing them.
2209 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
Evan Cheng3d794782008-01-11 23:10:11 +00002210 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +00002211
2212 // If this is a struct-return function, don't print the hidden
2213 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002214 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002215 assert(I != E && "Invalid struct return function!");
2216 ++I;
Evan Cheng3d794782008-01-11 23:10:11 +00002217 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002218 }
2219
2220 for (; I != E; ++I) {
2221 if (PrintedArg) FunctionInnards << ", ";
Evan Cheng3d794782008-01-11 23:10:11 +00002222 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +00002223 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Duncan Sands1df98592010-02-16 11:11:14 +00002224 assert(ArgTy->isPointerTy());
Evan Cheng3d794782008-01-11 23:10:11 +00002225 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2226 }
2227 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002228 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
Chris Lattner0c54d892006-05-23 23:39:48 +00002229 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002230 ++Idx;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002231 }
2232 }
2233
Chris Lattner1f8c4a12002-09-20 22:32:30 +00002234 // Finish printing arguments... if this is a vararg function, print the ...,
2235 // unless there are no known types, in which case, we just emit ().
2236 //
Chris Lattner0c54d892006-05-23 23:39:48 +00002237 if (FT->isVarArg() && PrintedArg) {
2238 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00002239 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattner0c54d892006-05-23 23:39:48 +00002240 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00002241 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002242 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002243 FunctionInnards << ')';
Chris Lattner0c54d892006-05-23 23:39:48 +00002244
2245 // Get the return tpe for the function.
2246 const Type *RetTy;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002247 if (!isStructReturn)
Chris Lattner0c54d892006-05-23 23:39:48 +00002248 RetTy = F->getReturnType();
2249 else {
2250 // If this is a struct-return function, print the struct-return type.
2251 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2252 }
2253
2254 // Print out the return type and the signature built above.
Reid Spencer30f9e27f2007-01-09 06:38:06 +00002255 printType(Out, RetTy,
Devang Patel05988662008-09-25 21:00:45 +00002256 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002257 FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002258}
2259
Reid Spencer22586642006-12-17 20:24:50 +00002260static inline bool isFPIntBitCast(const Instruction &I) {
2261 if (!isa<BitCastInst>(I))
2262 return false;
2263 const Type *SrcTy = I.getOperand(0)->getType();
2264 const Type *DstTy = I.getType();
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002265 return (SrcTy->isFloatingPointTy() && DstTy->isIntegerTy()) ||
2266 (DstTy->isFloatingPointTy() && SrcTy->isIntegerTy());
Reid Spencer22586642006-12-17 20:24:50 +00002267}
2268
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002269void CWriter::printFunction(Function &F) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002270 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002271 bool isStructReturn = F.hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002272
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002273 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002274 Out << " {\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00002275
2276 // If this is a struct return function, handle the result with magic.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002277 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002278 const Type *StructTy =
2279 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2280 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002281 printType(Out, StructTy, false, "StructReturn");
Chris Lattner0c54d892006-05-23 23:39:48 +00002282 Out << "; /* Struct return temporary */\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002283
Chris Lattner0c54d892006-05-23 23:39:48 +00002284 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002285 printType(Out, F.arg_begin()->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002286 GetValueName(F.arg_begin()));
Chris Lattner0c54d892006-05-23 23:39:48 +00002287 Out << " = &StructReturn;\n";
2288 }
2289
2290 bool PrintedVar = false;
2291
Chris Lattner497e19a2002-05-09 20:39:03 +00002292 // print local variable information for the function
Reid Spencer941cfda2006-12-17 18:50:51 +00002293 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002294 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00002295 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002296 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00002297 Out << "; /* Address-exposed local */\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00002298 PrintedVar = true;
Owen Anderson1d0be152009-08-13 21:58:54 +00002299 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2300 !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00002301 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002302 printType(Out, I->getType(), false, GetValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002303 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002304
Chris Lattner84e66652003-05-03 07:11:00 +00002305 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2306 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002307 printType(Out, I->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002308 GetValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00002309 Out << ";\n";
2310 }
Chris Lattner0c54d892006-05-23 23:39:48 +00002311 PrintedVar = true;
Reid Spencer941cfda2006-12-17 18:50:51 +00002312 }
2313 // We need a temporary for the BitCast to use so it can pluck a value out
Reid Spencere4d87aa2006-12-23 06:05:41 +00002314 // of a union to do the BitCast. This is separate from the need for a
Reid Spencer941cfda2006-12-17 18:50:51 +00002315 // variable to hold the result of the BitCast.
Reid Spencer22586642006-12-17 20:24:50 +00002316 if (isFPIntBitCast(*I)) {
Bill Wendling145aad02007-02-23 22:45:08 +00002317 Out << " llvmBitCastUnion " << GetValueName(&*I)
Reid Spencer555a0b12006-12-11 20:39:15 +00002318 << "__BITCAST_TEMPORARY;\n";
Reid Spencer941cfda2006-12-17 18:50:51 +00002319 PrintedVar = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002320 }
Reid Spencer941cfda2006-12-17 18:50:51 +00002321 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002322
Chris Lattner0c54d892006-05-23 23:39:48 +00002323 if (PrintedVar)
2324 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002325
Chris Lattner395fd592004-12-13 21:52:52 +00002326 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00002327 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00002328
Chris Lattner16c7bb22002-05-09 02:28:59 +00002329 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002330 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002331 if (Loop *L = LI->getLoopFor(BB)) {
2332 if (L->getHeader() == BB && L->getParentLoop() == 0)
2333 printLoop(L);
2334 } else {
2335 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00002336 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002337 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002338
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002339 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002340}
2341
Chris Lattnercb3ad012004-05-09 20:41:32 +00002342void CWriter::printLoop(Loop *L) {
2343 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2344 << "' to make GCC happy */\n";
2345 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2346 BasicBlock *BB = L->getBlocks()[i];
2347 Loop *BBLoop = LI->getLoopFor(BB);
2348 if (BBLoop == L)
2349 printBasicBlock(BB);
2350 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00002351 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002352 }
2353 Out << " } while (1); /* end of syntactic loop '"
2354 << L->getHeader()->getName() << "' */\n";
2355}
2356
2357void CWriter::printBasicBlock(BasicBlock *BB) {
2358
2359 // Don't print the label for the basic block if there are no uses, or if
2360 // the only terminator use is the predecessor basic block's terminator.
2361 // We have to scan the use list because PHI nodes use basic blocks too but
2362 // do not require a label to be generated.
2363 //
2364 bool NeedsLabel = false;
2365 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2366 if (isGotoCodeNecessary(*PI, BB)) {
2367 NeedsLabel = true;
2368 break;
2369 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002370
Bill Wendling145aad02007-02-23 22:45:08 +00002371 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002372
Chris Lattnercb3ad012004-05-09 20:41:32 +00002373 // Output all of the instructions in the basic block...
2374 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2375 ++II) {
2376 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002377 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2378 !isInlineAsm(*II))
Chris Lattnercb3ad012004-05-09 20:41:32 +00002379 outputLValue(II);
2380 else
2381 Out << " ";
Chris Lattnere56d9462008-05-31 09:23:55 +00002382 writeInstComputationInline(*II);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002383 Out << ";\n";
2384 }
2385 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002386
Chris Lattnere56d9462008-05-31 09:23:55 +00002387 // Don't emit prefix or suffix for the terminator.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002388 visit(*BB->getTerminator());
2389}
2390
2391
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002392// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00002393// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002394//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002395void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002396 // If this is a struct return function, return the temporary struct.
Devang Patel41e23972008-03-03 21:46:28 +00002397 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002398
2399 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002400 Out << " return StructReturn;\n";
2401 return;
2402 }
2403
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002404 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00002405 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002406 &*--I.getParent()->getParent()->end() == I.getParent() &&
2407 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002408 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00002409 }
Chris Lattner44408262002-05-09 03:50:42 +00002410
Dan Gohman76612792008-04-23 21:49:29 +00002411 if (I.getNumOperands() > 1) {
2412 Out << " {\n";
2413 Out << " ";
2414 printType(Out, I.getParent()->getParent()->getReturnType());
2415 Out << " llvm_cbe_mrv_temp = {\n";
2416 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2417 Out << " ";
2418 writeOperand(I.getOperand(i));
2419 if (i != e - 1)
2420 Out << ",";
2421 Out << "\n";
2422 }
2423 Out << " };\n";
2424 Out << " return llvm_cbe_mrv_temp;\n";
2425 Out << " }\n";
2426 return;
2427 }
2428
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002429 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002430 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002431 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002432 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002433 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002434 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002435}
2436
Chris Lattnera9f5e052003-04-22 20:19:52 +00002437void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002438
Chris Lattnera9f5e052003-04-22 20:19:52 +00002439 Out << " switch (";
2440 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00002441 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00002442 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00002443 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002444 Out << ";\n";
2445 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2446 Out << " case ";
2447 writeOperand(SI.getOperand(i));
2448 Out << ":\n";
2449 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00002450 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002451 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattner7896c9f2009-12-03 00:50:42 +00002452 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00002453 Out << " break;\n";
2454 }
2455 Out << " }\n";
2456}
2457
Chris Lattnerab21db72009-10-28 00:19:10 +00002458void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
Chris Lattnerf0dca282009-10-27 21:21:06 +00002459 Out << " goto *(void*)(";
2460 writeOperand(IBI.getOperand(0));
2461 Out << ");\n";
2462}
2463
Chris Lattnera9d12c02004-10-16 18:12:13 +00002464void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00002465 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00002466}
2467
Chris Lattnercb3ad012004-05-09 20:41:32 +00002468bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2469 /// FIXME: This should be reenabled, but loop reordering safe!!
2470 return true;
2471
Chris Lattner7896c9f2009-12-03 00:50:42 +00002472 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
Chris Lattner67c2d182005-03-18 16:12:37 +00002473 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002474
2475 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00002476
Chris Lattnercb3ad012004-05-09 20:41:32 +00002477 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002478 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002479 return false;
2480}
2481
John Criswell57bbfce2004-10-20 14:38:39 +00002482void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00002483 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00002484 unsigned Indent) {
2485 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2486 PHINode *PN = cast<PHINode>(I);
2487 // Now we have to do the printing.
2488 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2489 if (!isa<UndefValue>(IV)) {
2490 Out << std::string(Indent, ' ');
Bill Wendling145aad02007-02-23 22:45:08 +00002491 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
John Criswell57bbfce2004-10-20 14:38:39 +00002492 writeOperand(IV);
2493 Out << "; /* for PHI node */\n";
2494 }
2495 }
2496}
2497
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002498void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00002499 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002500 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00002501 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002502 writeOperand(Succ);
2503 Out << ";\n";
2504 }
2505}
2506
Misha Brukman37f92e22003-09-11 22:34:13 +00002507// Branch instruction printing - Avoid printing out a branch to a basic block
2508// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002509//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002510void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002511
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002512 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002513 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002514 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002515 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002516 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002517
John Criswell57bbfce2004-10-20 14:38:39 +00002518 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002519 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002520
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002521 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002522 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00002523 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002524 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002525 }
2526 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00002527 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002528 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002529 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002530 Out << ") {\n";
2531
John Criswell57bbfce2004-10-20 14:38:39 +00002532 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002533 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002534 }
2535
2536 Out << " }\n";
2537 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00002538 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002539 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002540 }
2541 Out << "\n";
2542}
2543
Chris Lattner84e66652003-05-03 07:11:00 +00002544// PHI nodes get copied into temporary values at the end of predecessor basic
2545// blocks. We now need to copy these temporary values into the REAL value for
2546// the PHI.
2547void CWriter::visitPHINode(PHINode &I) {
2548 writeOperand(&I);
2549 Out << "__PHI_TEMPORARY";
2550}
2551
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002552
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002553void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002554 // binary instructions, shift instructions, setCond instructions.
Duncan Sands1df98592010-02-16 11:11:14 +00002555 assert(!I.getType()->isPointerTy());
Brian Gaeke031a1122003-06-23 20:00:51 +00002556
2557 // We must cast the results of binary operations which might be promoted.
2558 bool needsCast = false;
Owen Anderson1d0be152009-08-13 21:58:54 +00002559 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2560 (I.getType() == Type::getInt16Ty(I.getContext()))
2561 || (I.getType() == Type::getFloatTy(I.getContext()))) {
Brian Gaeke031a1122003-06-23 20:00:51 +00002562 needsCast = true;
2563 Out << "((";
Reid Spencer251f2142007-01-09 17:09:09 +00002564 printType(Out, I.getType(), false);
Brian Gaeke031a1122003-06-23 20:00:51 +00002565 Out << ")(";
2566 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002567
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002568 // If this is a negation operation, print it out as such. For FP, we don't
2569 // want to print "-0.0 - X".
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002570 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00002571 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002572 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00002573 Out << ")";
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002574 } else if (BinaryOperator::isFNeg(&I)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002575 Out << "-(";
2576 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2577 Out << ")";
Reid Spencer0a783f72006-11-02 01:53:59 +00002578 } else if (I.getOpcode() == Instruction::FRem) {
Chris Lattner57da2522005-08-23 20:22:50 +00002579 // Output a call to fmod/fmodf instead of emitting a%b
Owen Anderson1d0be152009-08-13 21:58:54 +00002580 if (I.getType() == Type::getFloatTy(I.getContext()))
Chris Lattner57da2522005-08-23 20:22:50 +00002581 Out << "fmodf(";
Owen Anderson1d0be152009-08-13 21:58:54 +00002582 else if (I.getType() == Type::getDoubleTy(I.getContext()))
Chris Lattner57da2522005-08-23 20:22:50 +00002583 Out << "fmod(";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00002584 else // all 3 flavors of long double
2585 Out << "fmodl(";
Chris Lattner57da2522005-08-23 20:22:50 +00002586 writeOperand(I.getOperand(0));
2587 Out << ", ";
2588 writeOperand(I.getOperand(1));
2589 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002590 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +00002591
2592 // Write out the cast of the instruction's value back to the proper type
2593 // if necessary.
2594 bool NeedsClosingParens = writeInstructionCast(I);
2595
2596 // Certain instructions require the operand to be forced to a specific type
2597 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2598 // below for operand 1
2599 writeOperandWithCast(I.getOperand(0), I.getOpcode());
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002600
2601 switch (I.getOpcode()) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002602 case Instruction::Add:
2603 case Instruction::FAdd: Out << " + "; break;
2604 case Instruction::Sub:
2605 case Instruction::FSub: Out << " - "; break;
2606 case Instruction::Mul:
2607 case Instruction::FMul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00002608 case Instruction::URem:
2609 case Instruction::SRem:
Reid Spencer832254e2007-02-02 02:16:23 +00002610 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00002611 case Instruction::UDiv:
2612 case Instruction::SDiv:
Reid Spencer832254e2007-02-02 02:16:23 +00002613 case Instruction::FDiv: Out << " / "; break;
2614 case Instruction::And: Out << " & "; break;
2615 case Instruction::Or: Out << " | "; break;
2616 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002617 case Instruction::Shl : Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00002618 case Instruction::LShr:
2619 case Instruction::AShr: Out << " >> "; break;
Torok Edwindac237e2009-07-08 20:53:28 +00002620 default:
2621#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00002622 errs() << "Invalid operator type!" << I;
Torok Edwindac237e2009-07-08 20:53:28 +00002623#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002624 llvm_unreachable(0);
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002625 }
2626
Reid Spencer1628cec2006-10-26 06:15:43 +00002627 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2628 if (NeedsClosingParens)
2629 Out << "))";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002630 }
2631
Brian Gaeke031a1122003-06-23 20:00:51 +00002632 if (needsCast) {
2633 Out << "))";
2634 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002635}
2636
Reid Spencere4d87aa2006-12-23 06:05:41 +00002637void CWriter::visitICmpInst(ICmpInst &I) {
2638 // We must cast the results of icmp which might be promoted.
2639 bool needsCast = false;
2640
2641 // Write out the cast of the instruction's value back to the proper type
2642 // if necessary.
2643 bool NeedsClosingParens = writeInstructionCast(I);
2644
2645 // Certain icmp predicate require the operand to be forced to a specific type
2646 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2647 // below for operand 1
Chris Lattner5bda9e42007-09-15 06:51:03 +00002648 writeOperandWithCast(I.getOperand(0), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002649
2650 switch (I.getPredicate()) {
2651 case ICmpInst::ICMP_EQ: Out << " == "; break;
2652 case ICmpInst::ICMP_NE: Out << " != "; break;
2653 case ICmpInst::ICMP_ULE:
2654 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2655 case ICmpInst::ICMP_UGE:
2656 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2657 case ICmpInst::ICMP_ULT:
2658 case ICmpInst::ICMP_SLT: Out << " < "; break;
2659 case ICmpInst::ICMP_UGT:
2660 case ICmpInst::ICMP_SGT: Out << " > "; break;
Torok Edwindac237e2009-07-08 20:53:28 +00002661 default:
2662#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00002663 errs() << "Invalid icmp predicate!" << I;
Torok Edwindac237e2009-07-08 20:53:28 +00002664#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002665 llvm_unreachable(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002666 }
2667
Chris Lattner5bda9e42007-09-15 06:51:03 +00002668 writeOperandWithCast(I.getOperand(1), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002669 if (NeedsClosingParens)
2670 Out << "))";
2671
2672 if (needsCast) {
2673 Out << "))";
2674 }
2675}
2676
2677void CWriter::visitFCmpInst(FCmpInst &I) {
Reid Spencerb801a272007-01-08 06:58:32 +00002678 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2679 Out << "0";
2680 return;
2681 }
2682 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2683 Out << "1";
2684 return;
2685 }
2686
2687 const char* op = 0;
2688 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002689 default: llvm_unreachable("Illegal FCmp predicate");
Reid Spencerb801a272007-01-08 06:58:32 +00002690 case FCmpInst::FCMP_ORD: op = "ord"; break;
2691 case FCmpInst::FCMP_UNO: op = "uno"; break;
2692 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2693 case FCmpInst::FCMP_UNE: op = "une"; break;
2694 case FCmpInst::FCMP_ULT: op = "ult"; break;
2695 case FCmpInst::FCMP_ULE: op = "ule"; break;
2696 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2697 case FCmpInst::FCMP_UGE: op = "uge"; break;
2698 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2699 case FCmpInst::FCMP_ONE: op = "one"; break;
2700 case FCmpInst::FCMP_OLT: op = "olt"; break;
2701 case FCmpInst::FCMP_OLE: op = "ole"; break;
2702 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2703 case FCmpInst::FCMP_OGE: op = "oge"; break;
2704 }
2705
2706 Out << "llvm_fcmp_" << op << "(";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002707 // Write the first operand
2708 writeOperand(I.getOperand(0));
Reid Spencerb801a272007-01-08 06:58:32 +00002709 Out << ", ";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002710 // Write the second operand
2711 writeOperand(I.getOperand(1));
Reid Spencerb801a272007-01-08 06:58:32 +00002712 Out << ")";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002713}
2714
Reid Spencer555a0b12006-12-11 20:39:15 +00002715static const char * getFloatBitCastField(const Type *Ty) {
2716 switch (Ty->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002717 default: llvm_unreachable("Invalid Type");
Reid Spencer47857812006-12-31 05:55:36 +00002718 case Type::FloatTyID: return "Float";
Reid Spencer47857812006-12-31 05:55:36 +00002719 case Type::DoubleTyID: return "Double";
Reid Spencera54b7cb2007-01-12 07:05:14 +00002720 case Type::IntegerTyID: {
2721 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2722 if (NumBits <= 32)
2723 return "Int32";
2724 else
2725 return "Int64";
2726 }
Reid Spencer555a0b12006-12-11 20:39:15 +00002727 }
2728}
2729
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002730void CWriter::visitCastInst(CastInst &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002731 const Type *DstTy = I.getType();
2732 const Type *SrcTy = I.getOperand(0)->getType();
Reid Spencer22586642006-12-17 20:24:50 +00002733 if (isFPIntBitCast(I)) {
Chris Lattnere56d9462008-05-31 09:23:55 +00002734 Out << '(';
Reid Spencer555a0b12006-12-11 20:39:15 +00002735 // These int<->float and long<->double casts need to be handled specially
Bill Wendling145aad02007-02-23 22:45:08 +00002736 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002737 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2738 writeOperand(I.getOperand(0));
Bill Wendling145aad02007-02-23 22:45:08 +00002739 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002740 << getFloatBitCastField(I.getType());
Chris Lattnere56d9462008-05-31 09:23:55 +00002741 Out << ')';
2742 return;
2743 }
2744
2745 Out << '(';
2746 printCast(I.getOpcode(), SrcTy, DstTy);
2747
2748 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
Owen Anderson1d0be152009-08-13 21:58:54 +00002749 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2750 I.getOpcode() == Instruction::SExt)
Chris Lattnere56d9462008-05-31 09:23:55 +00002751 Out << "0-";
2752
2753 writeOperand(I.getOperand(0));
2754
Owen Anderson1d0be152009-08-13 21:58:54 +00002755 if (DstTy == Type::getInt1Ty(I.getContext()) &&
Chris Lattnere56d9462008-05-31 09:23:55 +00002756 (I.getOpcode() == Instruction::Trunc ||
2757 I.getOpcode() == Instruction::FPToUI ||
2758 I.getOpcode() == Instruction::FPToSI ||
2759 I.getOpcode() == Instruction::PtrToInt)) {
2760 // Make sure we really get a trunc to bool by anding the operand with 1
2761 Out << "&1u";
Reid Spencer3da59db2006-11-27 01:05:10 +00002762 }
Chris Lattner72623362007-05-03 02:57:13 +00002763 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002764}
2765
Chris Lattner9f24a072004-03-12 05:52:14 +00002766void CWriter::visitSelectInst(SelectInst &I) {
2767 Out << "((";
2768 writeOperand(I.getCondition());
2769 Out << ") ? (";
2770 writeOperand(I.getTrueValue());
2771 Out << ") : (";
2772 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00002773 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00002774}
2775
2776
Chris Lattnerc2421432004-05-09 04:30:20 +00002777void CWriter::lowerIntrinsics(Function &F) {
Reid Spencer69f80a62007-04-12 21:00:45 +00002778 // This is used to keep track of intrinsics that get generated to a lowered
2779 // function. We must generate the prototypes before the function body which
2780 // will only be expanded on first use (by the loop below).
2781 std::vector<Function*> prototypesToGen;
2782
2783 // Examine all the instructions in this function to find the intrinsics that
2784 // need to be lowered.
Jeff Cohen614408d2007-04-13 22:52:03 +00002785 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
Chris Lattnerc2421432004-05-09 04:30:20 +00002786 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2787 if (CallInst *CI = dyn_cast<CallInst>(I++))
2788 if (Function *F = CI->getCalledFunction())
2789 switch (F->getIntrinsicID()) {
2790 case Intrinsic::not_intrinsic:
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00002791 case Intrinsic::memory_barrier:
Chris Lattnerc2421432004-05-09 04:30:20 +00002792 case Intrinsic::vastart:
2793 case Intrinsic::vacopy:
2794 case Intrinsic::vaend:
2795 case Intrinsic::returnaddress:
2796 case Intrinsic::frameaddress:
2797 case Intrinsic::setjmp:
2798 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00002799 case Intrinsic::prefetch:
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00002800 case Intrinsic::powi:
Chris Lattner4e220122008-03-02 08:47:13 +00002801 case Intrinsic::x86_sse_cmp_ss:
2802 case Intrinsic::x86_sse_cmp_ps:
2803 case Intrinsic::x86_sse2_cmp_sd:
2804 case Intrinsic::x86_sse2_cmp_pd:
Chris Lattnerff939212008-03-02 08:54:27 +00002805 case Intrinsic::ppc_altivec_lvsl:
Chris Lattner4e220122008-03-02 08:47:13 +00002806 // We directly implement these intrinsics
Chris Lattnerc2421432004-05-09 04:30:20 +00002807 break;
2808 default:
Chris Lattner87242152006-03-13 23:09:05 +00002809 // If this is an intrinsic that directly corresponds to a GCC
2810 // builtin, we handle it.
2811 const char *BuiltinName = "";
2812#define GET_GCC_BUILTIN_NAME
2813#include "llvm/Intrinsics.gen"
2814#undef GET_GCC_BUILTIN_NAME
2815 // If we handle it, don't lower it.
2816 if (BuiltinName[0]) break;
2817
Chris Lattnerc2421432004-05-09 04:30:20 +00002818 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00002819 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002820 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00002821 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00002822
Reid Spencer519e2392007-01-29 17:51:02 +00002823 IL->LowerIntrinsicCall(CI);
Chris Lattnerc2421432004-05-09 04:30:20 +00002824 if (Before) { // Move iterator to instruction after call
2825 I = Before; ++I;
2826 } else {
2827 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00002828 }
Reid Spencer69f80a62007-04-12 21:00:45 +00002829 // If the intrinsic got lowered to another call, and that call has
2830 // a definition then we need to make sure its prototype is emitted
2831 // before any calls to it.
2832 if (CallInst *Call = dyn_cast<CallInst>(I))
2833 if (Function *NewF = Call->getCalledFunction())
2834 if (!NewF->isDeclaration())
2835 prototypesToGen.push_back(NewF);
2836
Chris Lattner87242152006-03-13 23:09:05 +00002837 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00002838 }
Chris Lattner4ef51372004-02-14 00:31:10 +00002839
Reid Spencer69f80a62007-04-12 21:00:45 +00002840 // We may have collected some prototypes to emit in the loop above.
2841 // Emit them now, before the function that uses them is emitted. But,
2842 // be careful not to emit them twice.
2843 std::vector<Function*>::iterator I = prototypesToGen.begin();
2844 std::vector<Function*>::iterator E = prototypesToGen.end();
2845 for ( ; I != E; ++I) {
Reid Spencer57c5b182007-04-12 21:57:15 +00002846 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
Reid Spencer69f80a62007-04-12 21:00:45 +00002847 Out << '\n';
2848 printFunctionSignature(*I, true);
2849 Out << ";\n";
Reid Spencer69f80a62007-04-12 21:00:45 +00002850 }
2851 }
2852}
Chris Lattner4ef51372004-02-14 00:31:10 +00002853
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002854void CWriter::visitCallInst(CallInst &I) {
Chris Lattnerf6a048c2008-05-22 06:19:37 +00002855 if (isa<InlineAsm>(I.getOperand(0)))
2856 return visitInlineAsm(I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002857
Chris Lattner87242152006-03-13 23:09:05 +00002858 bool WroteCallee = false;
2859
Chris Lattner18ac3c82003-05-08 18:41:45 +00002860 // Handle intrinsic function calls first...
2861 if (Function *F = I.getCalledFunction())
Chris Lattner2299fec2008-03-02 08:29:41 +00002862 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2863 if (visitBuiltinCall(I, ID, WroteCallee))
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00002864 return;
Chris Lattner18ac3c82003-05-08 18:41:45 +00002865
Chris Lattner4394d512004-11-13 22:21:56 +00002866 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00002867
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002868 const PointerType *PTy = cast<PointerType>(Callee->getType());
2869 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2870
Chris Lattner0c54d892006-05-23 23:39:48 +00002871 // If this is a call to a struct-return function, assign to the first
2872 // parameter instead of passing it to the call.
Devang Patel05988662008-09-25 21:00:45 +00002873 const AttrListPtr &PAL = I.getAttributes();
Evan Cheng7723ab32008-01-12 18:53:07 +00002874 bool hasByVal = I.hasByValArgument();
Devang Patel41e23972008-03-03 21:46:28 +00002875 bool isStructRet = I.hasStructRetAttr();
Chris Lattner0c54d892006-05-23 23:39:48 +00002876 if (isStructRet) {
Chris Lattnere05252b42008-03-02 08:07:24 +00002877 writeOperandDeref(I.getOperand(1));
Evan Cheng3d794782008-01-11 23:10:11 +00002878 Out << " = ";
Chris Lattner0c54d892006-05-23 23:39:48 +00002879 }
2880
Chris Lattnerfe673d92005-05-06 06:53:07 +00002881 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattner0c54d892006-05-23 23:39:48 +00002882
2883 if (!WroteCallee) {
2884 // If this is an indirect call to a struct return function, we need to cast
Evan Cheng7723ab32008-01-12 18:53:07 +00002885 // the pointer. Ditto for indirect calls with byval arguments.
2886 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002887
Chris Lattner0c54d892006-05-23 23:39:48 +00002888 // GCC is a real PITA. It does not permit codegening casts of functions to
2889 // function pointers if they are in a call (it generates a trap instruction
2890 // instead!). We work around this by inserting a cast to void* in between
2891 // the function and the function pointer cast. Unfortunately, we can't just
2892 // form the constant expression here, because the folder will immediately
2893 // nuke it.
2894 //
2895 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2896 // that void* and function pointers have the same size. :( To deal with this
2897 // in the common case, we handle casts where the number of arguments passed
2898 // match exactly.
2899 //
2900 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
Reid Spencer3da59db2006-11-27 01:05:10 +00002901 if (CE->isCast())
Chris Lattner0c54d892006-05-23 23:39:48 +00002902 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2903 NeedsCast = true;
2904 Callee = RF;
2905 }
2906
2907 if (NeedsCast) {
2908 // Ok, just cast the pointer type.
2909 Out << "((";
Evan Cheng7723ab32008-01-12 18:53:07 +00002910 if (isStructRet)
Duncan Sandsdc024672007-11-27 13:23:08 +00002911 printStructReturnPointerFunctionType(Out, PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +00002912 cast<PointerType>(I.getCalledValue()->getType()));
Evan Cheng7723ab32008-01-12 18:53:07 +00002913 else if (hasByVal)
2914 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
2915 else
2916 printType(Out, I.getCalledValue()->getType());
Chris Lattner0c54d892006-05-23 23:39:48 +00002917 Out << ")(void*)";
2918 }
2919 writeOperand(Callee);
2920 if (NeedsCast) Out << ')';
2921 }
2922
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002923 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002924
Chris Lattner4394d512004-11-13 22:21:56 +00002925 unsigned NumDeclaredParams = FTy->getNumParams();
2926
Chris Lattner0c54d892006-05-23 23:39:48 +00002927 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2928 unsigned ArgNo = 0;
2929 if (isStructRet) { // Skip struct return argument.
2930 ++AI;
2931 ++ArgNo;
2932 }
2933
2934 bool PrintedArg = false;
Evan Cheng3d794782008-01-11 23:10:11 +00002935 for (; AI != AE; ++AI, ++ArgNo) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002936 if (PrintedArg) Out << ", ";
2937 if (ArgNo < NumDeclaredParams &&
2938 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002939 Out << '(';
Reid Spencer0ae96932007-01-07 03:24:48 +00002940 printType(Out, FTy->getParamType(ArgNo),
Devang Patel05988662008-09-25 21:00:45 +00002941 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002942 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00002943 }
Evan Cheng3d794782008-01-11 23:10:11 +00002944 // Check if the argument is expected to be passed by value.
Devang Patel05988662008-09-25 21:00:45 +00002945 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
Chris Lattnere05252b42008-03-02 08:07:24 +00002946 writeOperandDeref(*AI);
2947 else
2948 writeOperand(*AI);
Chris Lattner0c54d892006-05-23 23:39:48 +00002949 PrintedArg = true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002950 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002951 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00002952}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002953
Chris Lattner2299fec2008-03-02 08:29:41 +00002954/// visitBuiltinCall - Handle the call to the specified builtin. Returns true
Dan Gohmanf451cb82010-02-10 16:03:48 +00002955/// if the entire call is handled, return false if it wasn't handled, and
Chris Lattner2299fec2008-03-02 08:29:41 +00002956/// optionally set 'WroteCallee' if the callee has already been printed out.
2957bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
2958 bool &WroteCallee) {
2959 switch (ID) {
2960 default: {
2961 // If this is an intrinsic that directly corresponds to a GCC
2962 // builtin, we emit it here.
2963 const char *BuiltinName = "";
2964 Function *F = I.getCalledFunction();
2965#define GET_GCC_BUILTIN_NAME
2966#include "llvm/Intrinsics.gen"
2967#undef GET_GCC_BUILTIN_NAME
2968 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2969
2970 Out << BuiltinName;
2971 WroteCallee = true;
2972 return false;
2973 }
2974 case Intrinsic::memory_barrier:
Andrew Lenharth6ad150b2008-03-05 23:41:37 +00002975 Out << "__sync_synchronize()";
Chris Lattner2299fec2008-03-02 08:29:41 +00002976 return true;
2977 case Intrinsic::vastart:
2978 Out << "0; ";
2979
2980 Out << "va_start(*(va_list*)";
2981 writeOperand(I.getOperand(1));
2982 Out << ", ";
2983 // Output the last argument to the enclosing function.
2984 if (I.getParent()->getParent()->arg_empty()) {
Torok Edwindac237e2009-07-08 20:53:28 +00002985 std::string msg;
2986 raw_string_ostream Msg(msg);
2987 Msg << "The C backend does not currently support zero "
Chris Lattner2299fec2008-03-02 08:29:41 +00002988 << "argument varargs functions, such as '"
Torok Edwindac237e2009-07-08 20:53:28 +00002989 << I.getParent()->getParent()->getName() << "'!";
2990 llvm_report_error(Msg.str());
Chris Lattner2299fec2008-03-02 08:29:41 +00002991 }
2992 writeOperand(--I.getParent()->getParent()->arg_end());
2993 Out << ')';
2994 return true;
2995 case Intrinsic::vaend:
2996 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
2997 Out << "0; va_end(*(va_list*)";
2998 writeOperand(I.getOperand(1));
2999 Out << ')';
3000 } else {
3001 Out << "va_end(*(va_list*)0)";
3002 }
3003 return true;
3004 case Intrinsic::vacopy:
3005 Out << "0; ";
3006 Out << "va_copy(*(va_list*)";
3007 writeOperand(I.getOperand(1));
3008 Out << ", *(va_list*)";
3009 writeOperand(I.getOperand(2));
3010 Out << ')';
3011 return true;
3012 case Intrinsic::returnaddress:
3013 Out << "__builtin_return_address(";
3014 writeOperand(I.getOperand(1));
3015 Out << ')';
3016 return true;
3017 case Intrinsic::frameaddress:
3018 Out << "__builtin_frame_address(";
3019 writeOperand(I.getOperand(1));
3020 Out << ')';
3021 return true;
3022 case Intrinsic::powi:
3023 Out << "__builtin_powi(";
3024 writeOperand(I.getOperand(1));
3025 Out << ", ";
3026 writeOperand(I.getOperand(2));
3027 Out << ')';
3028 return true;
3029 case Intrinsic::setjmp:
3030 Out << "setjmp(*(jmp_buf*)";
3031 writeOperand(I.getOperand(1));
3032 Out << ')';
3033 return true;
3034 case Intrinsic::longjmp:
3035 Out << "longjmp(*(jmp_buf*)";
3036 writeOperand(I.getOperand(1));
3037 Out << ", ";
3038 writeOperand(I.getOperand(2));
3039 Out << ')';
3040 return true;
3041 case Intrinsic::prefetch:
3042 Out << "LLVM_PREFETCH((const void *)";
3043 writeOperand(I.getOperand(1));
3044 Out << ", ";
3045 writeOperand(I.getOperand(2));
3046 Out << ", ";
3047 writeOperand(I.getOperand(3));
3048 Out << ")";
3049 return true;
3050 case Intrinsic::stacksave:
3051 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3052 // to work around GCC bugs (see PR1809).
3053 Out << "0; *((void**)&" << GetValueName(&I)
3054 << ") = __builtin_stack_save()";
3055 return true;
Chris Lattner4e220122008-03-02 08:47:13 +00003056 case Intrinsic::x86_sse_cmp_ss:
3057 case Intrinsic::x86_sse_cmp_ps:
3058 case Intrinsic::x86_sse2_cmp_sd:
3059 case Intrinsic::x86_sse2_cmp_pd:
3060 Out << '(';
3061 printType(Out, I.getType());
3062 Out << ')';
3063 // Multiple GCC builtins multiplex onto this intrinsic.
3064 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003065 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
Chris Lattner4e220122008-03-02 08:47:13 +00003066 case 0: Out << "__builtin_ia32_cmpeq"; break;
3067 case 1: Out << "__builtin_ia32_cmplt"; break;
3068 case 2: Out << "__builtin_ia32_cmple"; break;
3069 case 3: Out << "__builtin_ia32_cmpunord"; break;
3070 case 4: Out << "__builtin_ia32_cmpneq"; break;
3071 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3072 case 6: Out << "__builtin_ia32_cmpnle"; break;
3073 case 7: Out << "__builtin_ia32_cmpord"; break;
3074 }
3075 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3076 Out << 'p';
3077 else
3078 Out << 's';
3079 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3080 Out << 's';
3081 else
3082 Out << 'd';
3083
3084 Out << "(";
3085 writeOperand(I.getOperand(1));
3086 Out << ", ";
3087 writeOperand(I.getOperand(2));
3088 Out << ")";
3089 return true;
Chris Lattnerff939212008-03-02 08:54:27 +00003090 case Intrinsic::ppc_altivec_lvsl:
3091 Out << '(';
3092 printType(Out, I.getType());
3093 Out << ')';
3094 Out << "__builtin_altivec_lvsl(0, (void*)";
3095 writeOperand(I.getOperand(1));
3096 Out << ")";
3097 return true;
Chris Lattner2299fec2008-03-02 08:29:41 +00003098 }
3099}
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003100
3101//This converts the llvm constraint string to something gcc is expecting.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003102//TODO: work out platform independent constraints and factor those out
Andrew Lenharth238581f2006-11-28 19:56:02 +00003103// of the per target tables
3104// handle multiple constraint codes
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003105std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003106 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3107
Chris Lattneraf76e592009-08-22 20:48:53 +00003108 // Grab the translation table from MCAsmInfo if it exists.
Chris Lattnerc0dba722010-01-17 18:22:35 +00003109 const MCAsmInfo *TargetAsm;
3110 std::string Triple = TheModule->getTargetTriple();
3111 if (Triple.empty())
3112 Triple = llvm::sys::getHostTriple();
3113
3114 std::string E;
3115 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3116 TargetAsm = Match->createAsmInfo(Triple);
3117 else
3118 return c.Codes[0];
3119
3120 const char *const *table = TargetAsm->getAsmCBE();
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003121
Daniel Dunbar51b198a2009-07-15 20:24:03 +00003122 // Search the translation table if it exists.
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003123 for (int i = 0; table && table[i]; i += 2)
Chris Lattnerc0dba722010-01-17 18:22:35 +00003124 if (c.Codes[0] == table[i]) {
3125 delete TargetAsm;
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003126 return table[i+1];
Chris Lattnerc0dba722010-01-17 18:22:35 +00003127 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003128
Daniel Dunbar51b198a2009-07-15 20:24:03 +00003129 // Default is identity.
Chris Lattnerc0dba722010-01-17 18:22:35 +00003130 delete TargetAsm;
Andrew Lenharth85f22282006-11-28 22:25:32 +00003131 return c.Codes[0];
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003132}
3133
3134//TODO: import logic from AsmPrinter.cpp
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003135static std::string gccifyAsm(std::string asmstr) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003136 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3137 if (asmstr[i] == '\n')
3138 asmstr.replace(i, 1, "\\n");
3139 else if (asmstr[i] == '\t')
3140 asmstr.replace(i, 1, "\\t");
3141 else if (asmstr[i] == '$') {
3142 if (asmstr[i + 1] == '{') {
3143 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3144 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3145 std::string n = "%" +
3146 asmstr.substr(a + 1, b - a - 1) +
3147 asmstr.substr(i + 2, a - i - 2);
3148 asmstr.replace(i, b - i + 1, n);
3149 i += n.size() - 1;
3150 } else
3151 asmstr.replace(i, 1, "%");
3152 }
3153 else if (asmstr[i] == '%')//grr
3154 { asmstr.replace(i, 1, "%%"); ++i;}
3155
3156 return asmstr;
3157}
3158
Andrew Lenharth238581f2006-11-28 19:56:02 +00003159//TODO: assumptions about what consume arguments from the call are likely wrong
3160// handle communitivity
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003161void CWriter::visitInlineAsm(CallInst &CI) {
3162 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003163 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003164
3165 std::vector<std::pair<Value*, int> > ResultVals;
Owen Anderson1d0be152009-08-13 21:58:54 +00003166 if (CI.getType() == Type::getVoidTy(CI.getContext()))
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003167 ;
3168 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3169 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3170 ResultVals.push_back(std::make_pair(&CI, (int)i));
3171 } else {
3172 ResultVals.push_back(std::make_pair(&CI, -1));
3173 }
3174
Chris Lattner67f631d2008-06-04 18:03:28 +00003175 // Fix up the asm string for gcc and emit it.
3176 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3177 Out << " :";
3178
3179 unsigned ValueCount = 0;
3180 bool IsFirst = true;
3181
3182 // Convert over all the output constraints.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003183 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
Chris Lattner67f631d2008-06-04 18:03:28 +00003184 E = Constraints.end(); I != E; ++I) {
3185
3186 if (I->Type != InlineAsm::isOutput) {
3187 ++ValueCount;
3188 continue; // Ignore non-output constraints.
3189 }
3190
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003191 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003192 std::string C = InterpretASMConstraint(*I);
3193 if (C.empty()) continue;
3194
Chris Lattner67f631d2008-06-04 18:03:28 +00003195 if (!IsFirst) {
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003196 Out << ", ";
Chris Lattner67f631d2008-06-04 18:03:28 +00003197 IsFirst = false;
3198 }
3199
3200 // Unpack the dest.
3201 Value *DestVal;
3202 int DestValNo = -1;
3203
3204 if (ValueCount < ResultVals.size()) {
3205 DestVal = ResultVals[ValueCount].first;
3206 DestValNo = ResultVals[ValueCount].second;
3207 } else
3208 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3209
3210 if (I->isEarlyClobber)
3211 C = "&"+C;
3212
3213 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3214 if (DestValNo != -1)
3215 Out << ".field" << DestValNo; // Multiple retvals.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003216 Out << ")";
Chris Lattner67f631d2008-06-04 18:03:28 +00003217 ++ValueCount;
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003218 }
Chris Lattner67f631d2008-06-04 18:03:28 +00003219
3220
3221 // Convert over all the input constraints.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003222 Out << "\n :";
Chris Lattner67f631d2008-06-04 18:03:28 +00003223 IsFirst = true;
3224 ValueCount = 0;
3225 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3226 E = Constraints.end(); I != E; ++I) {
3227 if (I->Type != InlineAsm::isInput) {
3228 ++ValueCount;
3229 continue; // Ignore non-input constraints.
3230 }
3231
3232 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3233 std::string C = InterpretASMConstraint(*I);
3234 if (C.empty()) continue;
3235
3236 if (!IsFirst) {
Chris Lattner687a4cb2008-05-22 06:29:38 +00003237 Out << ", ";
Chris Lattner67f631d2008-06-04 18:03:28 +00003238 IsFirst = false;
3239 }
3240
3241 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3242 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3243
3244 Out << "\"" << C << "\"(";
3245 if (!I->isIndirect)
3246 writeOperand(SrcVal);
3247 else
3248 writeOperandDeref(SrcVal);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003249 Out << ")";
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003250 }
Chris Lattner67f631d2008-06-04 18:03:28 +00003251
3252 // Convert over the clobber constraints.
3253 IsFirst = true;
Chris Lattner67f631d2008-06-04 18:03:28 +00003254 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3255 E = Constraints.end(); I != E; ++I) {
3256 if (I->Type != InlineAsm::isClobber)
3257 continue; // Ignore non-input constraints.
3258
3259 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3260 std::string C = InterpretASMConstraint(*I);
3261 if (C.empty()) continue;
3262
3263 if (!IsFirst) {
3264 Out << ", ";
3265 IsFirst = false;
3266 }
3267
3268 Out << '\"' << C << '"';
3269 }
3270
Andrew Lenharthf45148e2006-11-28 23:07:32 +00003271 Out << ")";
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003272}
3273
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003274void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003275 Out << '(';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00003276 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003277 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00003278 printType(Out, I.getType()->getElementType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003279 Out << ')';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003280 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003281 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003282 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003283 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003284 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003285}
3286
Chris Lattnere05252b42008-03-02 08:07:24 +00003287void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohman9f8d5712008-07-24 17:57:48 +00003288 gep_type_iterator E, bool Static) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003289
3290 // If there are no indices, just print out the pointer.
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00003291 if (I == E) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003292 writeOperand(Ptr);
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00003293 return;
3294 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003295
3296 // Find out if the last index is into a vector. If so, we have to print this
3297 // specially. Since vectors can't have elements of indexable type, only the
3298 // last index could possibly be of a vector element.
3299 const VectorType *LastIndexIsVector = 0;
3300 {
3301 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3302 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
Nick Hildenbrandte548f002002-09-25 20:29:26 +00003303 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003304
3305 Out << "(";
3306
3307 // If the last index is into a vector, we can't print it as &a[i][j] because
3308 // we can't index into a vector with j in GCC. Instead, emit this as
3309 // (((float*)&a[i])+j)
3310 if (LastIndexIsVector) {
3311 Out << "((";
3312 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3313 Out << ")(";
3314 }
3315
3316 Out << '&';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003317
Chris Lattnere05252b42008-03-02 08:07:24 +00003318 // If the first index is 0 (very typical) we can do a number of
3319 // simplifications to clean up the code.
3320 Value *FirstOp = I.getOperand();
3321 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3322 // First index isn't simple, print it the hard way.
3323 writeOperand(Ptr);
3324 } else {
3325 ++I; // Skip the zero index.
Nick Hildenbrandte548f002002-09-25 20:29:26 +00003326
Chris Lattnere05252b42008-03-02 08:07:24 +00003327 // Okay, emit the first operand. If Ptr is something that is already address
3328 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3329 if (isAddressExposed(Ptr)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00003330 writeOperandInternal(Ptr, Static);
Duncan Sands1df98592010-02-16 11:11:14 +00003331 } else if (I != E && (*I)->isStructTy()) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003332 // If we didn't already emit the first operand, see if we can print it as
3333 // P->f instead of "P[0].f"
3334 writeOperand(Ptr);
3335 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3336 ++I; // eat the struct index as well.
3337 } else {
3338 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3339 Out << "(*";
3340 writeOperand(Ptr);
3341 Out << ")";
Chris Lattner23e90702003-11-25 20:49:55 +00003342 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003343 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00003344
Chris Lattnere05252b42008-03-02 08:07:24 +00003345 for (; I != E; ++I) {
Duncan Sands1df98592010-02-16 11:11:14 +00003346 if ((*I)->isStructTy()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003347 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
Duncan Sands1df98592010-02-16 11:11:14 +00003348 } else if ((*I)->isArrayTy()) {
Dan Gohman193c2352008-06-02 21:30:49 +00003349 Out << ".array[";
3350 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3351 Out << ']';
Duncan Sands1df98592010-02-16 11:11:14 +00003352 } else if (!(*I)->isVectorTy()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003353 Out << '[';
Chris Lattner96b207c2007-09-22 20:16:48 +00003354 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003355 Out << ']';
Chris Lattnere05252b42008-03-02 08:07:24 +00003356 } else {
3357 // If the last index is into a vector, then print it out as "+j)". This
3358 // works with the 'LastIndexIsVector' code above.
3359 if (isa<Constant>(I.getOperand()) &&
3360 cast<Constant>(I.getOperand())->isNullValue()) {
3361 Out << "))"; // avoid "+0".
3362 } else {
3363 Out << ")+(";
3364 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3365 Out << "))";
3366 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003367 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003368 }
3369 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003370}
3371
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003372void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3373 bool IsVolatile, unsigned Alignment) {
3374
3375 bool IsUnaligned = Alignment &&
3376 Alignment < TD->getABITypeAlignment(OperandType);
3377
3378 if (!IsUnaligned)
3379 Out << '*';
3380 if (IsVolatile || IsUnaligned) {
Chris Lattner8399e022005-02-15 05:52:14 +00003381 Out << "((";
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003382 if (IsUnaligned)
3383 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3384 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3385 if (IsUnaligned) {
3386 Out << "; } ";
3387 if (IsVolatile) Out << "volatile ";
3388 Out << "*";
3389 }
Chris Lattnerb94388a2005-09-27 20:52:44 +00003390 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00003391 }
3392
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003393 writeOperand(Operand);
Chris Lattner9d30e222005-02-14 16:47:52 +00003394
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003395 if (IsVolatile || IsUnaligned) {
Misha Brukman23ba0c52005-03-08 00:26:08 +00003396 Out << ')';
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003397 if (IsUnaligned)
3398 Out << "->data";
3399 }
3400}
3401
3402void CWriter::visitLoadInst(LoadInst &I) {
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003403 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3404 I.getAlignment());
3405
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003406}
3407
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003408void CWriter::visitStoreInst(StoreInst &I) {
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003409 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3410 I.isVolatile(), I.getAlignment());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003411 Out << " = ";
Reid Spencerbdc75082007-03-03 16:33:33 +00003412 Value *Operand = I.getOperand(0);
3413 Constant *BitMask = 0;
3414 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3415 if (!ITy->isPowerOf2ByteWidth())
3416 // We have a bit width that doesn't match an even power-of-2 byte
3417 // size. Consequently we must & the value with the type's bit mask
Owen Andersoneed707b2009-07-24 23:12:02 +00003418 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
Reid Spencerbdc75082007-03-03 16:33:33 +00003419 if (BitMask)
3420 Out << "((";
3421 writeOperand(Operand);
3422 if (BitMask) {
3423 Out << ") & ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00003424 printConstant(BitMask, false);
Reid Spencerbdc75082007-03-03 16:33:33 +00003425 Out << ")";
3426 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003427}
3428
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003429void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003430 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
Dan Gohman9f8d5712008-07-24 17:57:48 +00003431 gep_type_end(I), false);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003432}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00003433
Chris Lattner4d45bd02003-10-18 05:57:43 +00003434void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00003435 Out << "va_arg(*(va_list*)";
Chris Lattner4d45bd02003-10-18 05:57:43 +00003436 writeOperand(I.getOperand(0));
Andrew Lenharth558bc882005-06-18 18:34:52 +00003437 Out << ", ";
Chris Lattner7635ea42003-11-03 01:01:59 +00003438 printType(Out, I.getType());
Andrew Lenharth558bc882005-06-18 18:34:52 +00003439 Out << ");\n ";
Chris Lattner4d45bd02003-10-18 05:57:43 +00003440}
3441
Chris Lattner33a44d92008-03-02 03:52:39 +00003442void CWriter::visitInsertElementInst(InsertElementInst &I) {
3443 const Type *EltTy = I.getType()->getElementType();
3444 writeOperand(I.getOperand(0));
3445 Out << ";\n ";
3446 Out << "((";
3447 printType(Out, PointerType::getUnqual(EltTy));
3448 Out << ")(&" << GetValueName(&I) << "))[";
Chris Lattner33a44d92008-03-02 03:52:39 +00003449 writeOperand(I.getOperand(2));
Chris Lattner9152daf2008-03-02 08:10:16 +00003450 Out << "] = (";
3451 writeOperand(I.getOperand(1));
Chris Lattner33a44d92008-03-02 03:52:39 +00003452 Out << ")";
3453}
3454
Chris Lattner0452ed62008-03-02 03:57:08 +00003455void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3456 // We know that our operand is not inlined.
3457 Out << "((";
3458 const Type *EltTy =
3459 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3460 printType(Out, PointerType::getUnqual(EltTy));
3461 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3462 writeOperand(I.getOperand(1));
3463 Out << "]";
3464}
3465
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003466void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3467 Out << "(";
3468 printType(Out, SVI.getType());
3469 Out << "){ ";
3470 const VectorType *VT = SVI.getType();
3471 unsigned NumElts = VT->getNumElements();
3472 const Type *EltTy = VT->getElementType();
3473
3474 for (unsigned i = 0; i != NumElts; ++i) {
3475 if (i) Out << ", ";
3476 int SrcVal = SVI.getMaskValue(i);
3477 if ((unsigned)SrcVal >= NumElts*2) {
3478 Out << " 0/*undef*/ ";
3479 } else {
3480 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3481 if (isa<Instruction>(Op)) {
3482 // Do an extractelement of this value from the appropriate input.
3483 Out << "((";
3484 printType(Out, PointerType::getUnqual(EltTy));
3485 Out << ")(&" << GetValueName(Op)
Duncan Sands43e2a032008-05-27 11:50:51 +00003486 << "))[" << (SrcVal & (NumElts-1)) << "]";
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003487 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3488 Out << "0";
3489 } else {
Duncan Sands43e2a032008-05-27 11:50:51 +00003490 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
Dan Gohman9f8d5712008-07-24 17:57:48 +00003491 (NumElts-1)),
3492 false);
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003493 }
3494 }
3495 }
3496 Out << "}";
3497}
Chris Lattner0452ed62008-03-02 03:57:08 +00003498
Dan Gohman193c2352008-06-02 21:30:49 +00003499void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3500 // Start by copying the entire aggregate value into the result variable.
3501 writeOperand(IVI.getOperand(0));
3502 Out << ";\n ";
3503
3504 // Then do the insert to update the field.
3505 Out << GetValueName(&IVI);
3506 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3507 i != e; ++i) {
3508 const Type *IndexedTy =
3509 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
Duncan Sands1df98592010-02-16 11:11:14 +00003510 if (IndexedTy->isArrayTy())
Dan Gohman193c2352008-06-02 21:30:49 +00003511 Out << ".array[" << *i << "]";
3512 else
3513 Out << ".field" << *i;
3514 }
3515 Out << " = ";
3516 writeOperand(IVI.getOperand(1));
3517}
3518
3519void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3520 Out << "(";
3521 if (isa<UndefValue>(EVI.getOperand(0))) {
3522 Out << "(";
3523 printType(Out, EVI.getType());
3524 Out << ") 0/*UNDEF*/";
3525 } else {
3526 Out << GetValueName(EVI.getOperand(0));
3527 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3528 i != e; ++i) {
3529 const Type *IndexedTy =
3530 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
Duncan Sands1df98592010-02-16 11:11:14 +00003531 if (IndexedTy->isArrayTy())
Dan Gohman193c2352008-06-02 21:30:49 +00003532 Out << ".array[" << *i << "]";
3533 else
3534 Out << ".field" << *i;
3535 }
3536 }
3537 Out << ")";
3538}
3539
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00003540//===----------------------------------------------------------------------===//
3541// External Interface declaration
3542//===----------------------------------------------------------------------===//
3543
Chris Lattner1911fd42006-09-04 04:14:57 +00003544bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
David Greene71847812009-07-14 20:18:05 +00003545 formatted_raw_ostream &o,
Chris Lattner1911fd42006-09-04 04:14:57 +00003546 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00003547 CodeGenOpt::Level OptLevel) {
Chris Lattner211edae2010-02-02 21:06:45 +00003548 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Chris Lattner0431c962005-06-25 02:48:37 +00003549
Gordon Henriksence224772008-01-07 01:30:38 +00003550 PM.add(createGCLoweringPass());
Chris Lattner94f4f8e2004-02-13 23:00:29 +00003551 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00003552 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00003553 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00003554 PM.add(new CWriter(o));
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003555 PM.add(createGCInfoDeleter());
Chris Lattnerf31182a2004-02-13 23:18:48 +00003556 return false;
3557}