blob: 7fd54ad37976002e64ee4801a9d28b9f273d3bc7 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This library converts LLVM code to C code, compilable by GCC and other C
11// compilers.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CTargetMachine.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Module.h"
20#include "llvm/Instructions.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/Pass.h"
22#include "llvm/PassManager.h"
23#include "llvm/TypeSymbolTable.h"
24#include "llvm/Intrinsics.h"
25#include "llvm/IntrinsicInst.h"
26#include "llvm/InlineAsm.h"
Daniel Dunbar4baa5fe2009-08-03 04:03:51 +000027#include "llvm/ADT/StringExtras.h"
Chris Lattnera38b2872010-01-13 06:38:18 +000028#include "llvm/ADT/SmallString.h"
Daniel Dunbar4baa5fe2009-08-03 04:03:51 +000029#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include "llvm/Analysis/ConstantsScanner.h"
31#include "llvm/Analysis/FindUsedTypes.h"
32#include "llvm/Analysis/LoopInfo.h"
Anton Korobeynikov865e6752009-08-05 09:29:56 +000033#include "llvm/Analysis/ValueTracking.h"
Gordon Henriksendf87fdc2008-01-07 01:30:38 +000034#include "llvm/CodeGen/Passes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner31a54742010-01-16 21:57:06 +000036#include "llvm/Target/Mangler.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner621c44d2009-08-22 20:48:53 +000038#include "llvm/MC/MCAsmInfo.h"
Chris Lattner11d7dfa2010-01-13 21:12:34 +000039#include "llvm/MC/MCSymbol.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/Target/TargetData.h"
Daniel Dunbarfe5939f2009-07-15 20:24:03 +000041#include "llvm/Target/TargetRegistry.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042#include "llvm/Support/CallSite.h"
43#include "llvm/Support/CFG.h"
Edwin Török4d9756a2009-07-08 20:53:28 +000044#include "llvm/Support/ErrorHandling.h"
David Greene302008d2009-07-14 20:18:05 +000045#include "llvm/Support/FormattedStream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046#include "llvm/Support/GetElementPtrTypeIterator.h"
47#include "llvm/Support/InstVisitor.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048#include "llvm/Support/MathExtras.h"
Daniel Dunbar4baa5fe2009-08-03 04:03:51 +000049#include "llvm/System/Host.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050#include "llvm/Config/config.h"
51#include <algorithm>
52#include <sstream>
53using namespace llvm;
54
Daniel Dunbarc680b012009-07-25 06:49:55 +000055extern "C" void LLVMInitializeCBackendTarget() {
56 // Register the target.
Daniel Dunbare6ad1102009-08-04 04:02:45 +000057 RegisterTargetMachine<CTargetMachine> X(TheCBackendTarget);
Daniel Dunbarc680b012009-07-25 06:49:55 +000058}
Douglas Gregor1dc5ff42009-06-16 20:12:29 +000059
Dan Gohman089efff2008-05-13 00:00:25 +000060namespace {
Chris Lattner63ab9bb2010-01-17 18:22:35 +000061 class CBEMCAsmInfo : public MCAsmInfo {
62 public:
63 CBEMCAsmInfo() {
64 GlobalPrefix = "";
65 PrivateGlobalPrefix = "";
66 }
67 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000068 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
69 /// any unnamed structure types that are used by the program, and merges
70 /// external functions with the same name.
71 ///
72 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
73 public:
74 static char ID;
75 CBackendNameAllUsedStructsAndMergeFunctions()
Dan Gohman26f8c272008-09-04 17:05:41 +000076 : ModulePass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000077 void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequired<FindUsedTypes>();
79 }
80
81 virtual const char *getPassName() const {
82 return "C backend type canonicalizer";
83 }
84
85 virtual bool runOnModule(Module &M);
86 };
87
88 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
89
90 /// CWriter - This class is the main chunk of code that converts an LLVM
91 /// module to a C translation unit.
92 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
David Greene302008d2009-07-14 20:18:05 +000093 formatted_raw_ostream &Out;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094 IntrinsicLowering *IL;
95 Mangler *Mang;
96 LoopInfo *LI;
97 const Module *TheModule;
Chris Lattner621c44d2009-08-22 20:48:53 +000098 const MCAsmInfo* TAsm;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000099 const TargetData* TD;
100 std::map<const Type *, std::string> TypeNames;
101 std::map<const ConstantFP *, unsigned> FPConstantMap;
102 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
Chris Lattner8bbc8592008-03-02 08:07:24 +0000103 std::set<const Argument*> ByValParams;
Chris Lattnerf6e12012008-10-22 04:53:16 +0000104 unsigned FPCounter;
Owen Andersonde8a9442009-06-26 19:48:37 +0000105 unsigned OpaqueCounter;
Chris Lattnerb66867f2009-07-13 23:46:46 +0000106 DenseMap<const Value*, unsigned> AnonValueNumbers;
107 unsigned NextAnonValueNumber;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108
109 public:
110 static char ID;
David Greene302008d2009-07-14 20:18:05 +0000111 explicit CWriter(formatted_raw_ostream &o)
Dan Gohman26f8c272008-09-04 17:05:41 +0000112 : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0),
Chris Lattnerb66867f2009-07-13 23:46:46 +0000113 TheModule(0), TAsm(0), TD(0), OpaqueCounter(0), NextAnonValueNumber(0) {
Chris Lattnerf6e12012008-10-22 04:53:16 +0000114 FPCounter = 0;
115 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000116
117 virtual const char *getPassName() const { return "C backend"; }
118
119 void getAnalysisUsage(AnalysisUsage &AU) const {
120 AU.addRequired<LoopInfo>();
121 AU.setPreservesAll();
122 }
123
124 virtual bool doInitialization(Module &M);
125
126 bool runOnFunction(Function &F) {
Chris Lattner3ed055f2009-04-17 00:26:12 +0000127 // Do not codegen any 'available_externally' functions at all, they have
128 // definitions outside the translation unit.
129 if (F.hasAvailableExternallyLinkage())
130 return false;
131
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 LI = &getAnalysis<LoopInfo>();
133
134 // Get rid of intrinsics we can't handle.
135 lowerIntrinsics(F);
136
137 // Output all floating point constants that cannot be printed accurately.
138 printFloatingPointConstants(F);
139
140 printFunction(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 return false;
142 }
143
144 virtual bool doFinalization(Module &M) {
145 // Free memory...
Nuno Lopes6c857162009-01-13 23:35:49 +0000146 delete IL;
147 delete TD;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148 delete Mang;
Evan Cheng17254e62008-01-11 09:12:49 +0000149 FPConstantMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150 TypeNames.clear();
Evan Cheng17254e62008-01-11 09:12:49 +0000151 ByValParams.clear();
Chris Lattner8bbc8592008-03-02 08:07:24 +0000152 intrinsicPrototypesAlreadyGenerated.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 return false;
154 }
155
David Greene302008d2009-07-14 20:18:05 +0000156 raw_ostream &printType(formatted_raw_ostream &Out,
157 const Type *Ty,
158 bool isSigned = false,
159 const std::string &VariableName = "",
160 bool IgnoreName = false,
161 const AttrListPtr &PAL = AttrListPtr());
Owen Anderson847b99b2008-08-21 00:14:44 +0000162 std::ostream &printType(std::ostream &Out, const Type *Ty,
163 bool isSigned = false,
164 const std::string &VariableName = "",
165 bool IgnoreName = false,
Devang Pateld222f862008-09-25 21:00:45 +0000166 const AttrListPtr &PAL = AttrListPtr());
David Greene302008d2009-07-14 20:18:05 +0000167 raw_ostream &printSimpleType(formatted_raw_ostream &Out,
168 const Type *Ty,
169 bool isSigned,
170 const std::string &NameSoFar = "");
Owen Anderson847b99b2008-08-21 00:14:44 +0000171 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
172 bool isSigned,
173 const std::string &NameSoFar = "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174
David Greene302008d2009-07-14 20:18:05 +0000175 void printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
Devang Pateld222f862008-09-25 21:00:45 +0000176 const AttrListPtr &PAL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 const PointerType *Ty);
Chris Lattner8bbc8592008-03-02 08:07:24 +0000178
179 /// writeOperandDeref - Print the result of dereferencing the specified
180 /// operand with '*'. This is equivalent to printing '*' then using
181 /// writeOperand, but avoids excess syntax in some cases.
182 void writeOperandDeref(Value *Operand) {
183 if (isAddressExposed(Operand)) {
184 // Already something with an address exposed.
185 writeOperandInternal(Operand);
186 } else {
187 Out << "*(";
188 writeOperand(Operand);
189 Out << ")";
190 }
191 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000192
Dan Gohmanad831302008-07-24 17:57:48 +0000193 void writeOperand(Value *Operand, bool Static = false);
Chris Lattnerd70f5a82008-05-31 09:23:55 +0000194 void writeInstComputationInline(Instruction &I);
Dan Gohmanad831302008-07-24 17:57:48 +0000195 void writeOperandInternal(Value *Operand, bool Static = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196 void writeOperandWithCast(Value* Operand, unsigned Opcode);
Chris Lattner389c9142007-09-15 06:51:03 +0000197 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 bool writeInstructionCast(const Instruction &I);
199
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +0000200 void writeMemoryAccess(Value *Operand, const Type *OperandType,
201 bool IsVolatile, unsigned Alignment);
202
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 private :
204 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
205
206 void lowerIntrinsics(Function &F);
207
208 void printModule(Module *M);
209 void printModuleTypes(const TypeSymbolTable &ST);
Dan Gohman5d995b02008-06-02 21:30:49 +0000210 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 void printFloatingPointConstants(Function &F);
Chris Lattnerf6e12012008-10-22 04:53:16 +0000212 void printFloatingPointConstants(const Constant *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 void printFunctionSignature(const Function *F, bool Prototype);
214
215 void printFunction(Function &);
216 void printBasicBlock(BasicBlock *BB);
217 void printLoop(Loop *L);
218
219 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
Dan Gohmanad831302008-07-24 17:57:48 +0000220 void printConstant(Constant *CPV, bool Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221 void printConstantWithCast(Constant *CPV, unsigned Opcode);
Dan Gohmanad831302008-07-24 17:57:48 +0000222 bool printConstExprCast(const ConstantExpr *CE, bool Static);
223 void printConstantArray(ConstantArray *CPA, bool Static);
224 void printConstantVector(ConstantVector *CV, bool Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225
Chris Lattner8bbc8592008-03-02 08:07:24 +0000226 /// isAddressExposed - Return true if the specified value's name needs to
227 /// have its address taken in order to get a C value of the correct type.
228 /// This happens for global variables, byval parameters, and direct allocas.
229 bool isAddressExposed(const Value *V) const {
230 if (const Argument *A = dyn_cast<Argument>(V))
231 return ByValParams.count(A);
232 return isa<GlobalVariable>(V) || isDirectAlloca(V);
233 }
234
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235 // isInlinableInst - Attempt to inline instructions into their uses to build
236 // trees as much as possible. To do this, we have to consistently decide
237 // what is acceptable to inline, so that variable declarations don't get
238 // printed and an extra copy of the expr is not emitted.
239 //
240 static bool isInlinableInst(const Instruction &I) {
241 // Always inline cmp instructions, even if they are shared by multiple
242 // expressions. GCC generates horrible code if we don't.
243 if (isa<CmpInst>(I))
244 return true;
245
246 // Must be an expression, must be used exactly once. If it is dead, we
247 // emit it inline where it would go.
Owen Anderson35b47072009-08-13 21:58:54 +0000248 if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Dan Gohman5d995b02008-06-02 21:30:49 +0000250 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
251 isa<InsertValueInst>(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 // Don't inline a load across a store or other bad things!
253 return false;
254
Chris Lattnerf858a042008-03-02 05:41:07 +0000255 // Must not be used in inline asm, extractelement, or shufflevector.
256 if (I.hasOneUse()) {
257 const Instruction &User = cast<Instruction>(*I.use_back());
258 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
259 isa<ShuffleVectorInst>(User))
260 return false;
261 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262
263 // Only inline instruction it if it's use is in the same BB as the inst.
264 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
265 }
266
267 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
268 // variables which are accessed with the & operator. This causes GCC to
269 // generate significantly better code than to emit alloca calls directly.
270 //
271 static const AllocaInst *isDirectAlloca(const Value *V) {
272 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
273 if (!AI) return false;
274 if (AI->isArrayAllocation())
275 return 0; // FIXME: we can also inline fixed size array allocas!
276 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
277 return 0;
278 return AI;
279 }
280
281 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
282 static bool isInlineAsm(const Instruction& I) {
283 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
284 return true;
285 return false;
286 }
287
288 // Instruction visitation functions
289 friend class InstVisitor<CWriter>;
290
291 void visitReturnInst(ReturnInst &I);
292 void visitBranchInst(BranchInst &I);
293 void visitSwitchInst(SwitchInst &I);
Chris Lattner4c3800f2009-10-28 00:19:10 +0000294 void visitIndirectBrInst(IndirectBrInst &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295 void visitInvokeInst(InvokeInst &I) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000296 llvm_unreachable("Lowerinvoke pass didn't work!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297 }
298
299 void visitUnwindInst(UnwindInst &I) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000300 llvm_unreachable("Lowerinvoke pass didn't work!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000301 }
302 void visitUnreachableInst(UnreachableInst &I);
303
304 void visitPHINode(PHINode &I);
305 void visitBinaryOperator(Instruction &I);
306 void visitICmpInst(ICmpInst &I);
307 void visitFCmpInst(FCmpInst &I);
308
309 void visitCastInst (CastInst &I);
310 void visitSelectInst(SelectInst &I);
311 void visitCallInst (CallInst &I);
312 void visitInlineAsm(CallInst &I);
Chris Lattnera74b9182008-03-02 08:29:41 +0000313 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 void visitAllocaInst(AllocaInst &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 void visitLoadInst (LoadInst &I);
317 void visitStoreInst (StoreInst &I);
318 void visitGetElementPtrInst(GetElementPtrInst &I);
319 void visitVAArgInst (VAArgInst &I);
Chris Lattnerf41a7942008-03-02 03:52:39 +0000320
321 void visitInsertElementInst(InsertElementInst &I);
Chris Lattnera5f0bc02008-03-02 03:57:08 +0000322 void visitExtractElementInst(ExtractElementInst &I);
Chris Lattnerf858a042008-03-02 05:41:07 +0000323 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324
Dan Gohman5d995b02008-06-02 21:30:49 +0000325 void visitInsertValueInst(InsertValueInst &I);
326 void visitExtractValueInst(ExtractValueInst &I);
327
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000328 void visitInstruction(Instruction &I) {
Edwin Török4d9756a2009-07-08 20:53:28 +0000329#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +0000330 errs() << "C Writer does not know about " << I;
Edwin Török4d9756a2009-07-08 20:53:28 +0000331#endif
Edwin Törökbd448e32009-07-14 16:55:14 +0000332 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333 }
334
335 void outputLValue(Instruction *I) {
336 Out << " " << GetValueName(I) << " = ";
337 }
338
339 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
340 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
341 BasicBlock *Successor, unsigned Indent);
342 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
343 unsigned Indent);
Chris Lattner8bbc8592008-03-02 08:07:24 +0000344 void printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohmanad831302008-07-24 17:57:48 +0000345 gep_type_iterator E, bool Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346
347 std::string GetValueName(const Value *Operand);
348 };
349}
350
351char CWriter::ID = 0;
352
Chris Lattnerd2f59b82010-01-13 19:54:07 +0000353
Chris Lattnerd2f59b82010-01-13 19:54:07 +0000354static std::string Mangle(const std::string &S) {
355 std::string Result;
Chris Lattner11d7dfa2010-01-13 21:12:34 +0000356 raw_string_ostream OS(Result);
357 MCSymbol::printMangledName(S, OS, 0);
358 return OS.str();
Chris Lattnerd2f59b82010-01-13 19:54:07 +0000359}
360
361
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000362/// This method inserts names for any unnamed structure types that are used by
363/// the program, and removes names from structure types that are not used by the
364/// program.
365///
366bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
367 // Get a set of types that are used by the program...
368 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
369
370 // Loop over the module symbol table, removing types from UT that are
371 // already named, and removing names for types that are not used.
372 //
373 TypeSymbolTable &TST = M.getTypeSymbolTable();
374 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
375 TI != TE; ) {
376 TypeSymbolTable::iterator I = TI++;
377
Dan Gohman5d995b02008-06-02 21:30:49 +0000378 // If this isn't a struct or array type, remove it from our set of types
379 // to name. This simplifies emission later.
380 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
381 !isa<ArrayType>(I->second)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382 TST.remove(I);
383 } else {
384 // If this is not used, remove it from the symbol table.
385 std::set<const Type *>::iterator UTI = UT.find(I->second);
386 if (UTI == UT.end())
387 TST.remove(I);
388 else
389 UT.erase(UTI); // Only keep one name for this type.
390 }
391 }
392
393 // UT now contains types that are not named. Loop over it, naming
394 // structure types.
395 //
396 bool Changed = false;
397 unsigned RenameCounter = 0;
398 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
399 I != E; ++I)
Dan Gohman5d995b02008-06-02 21:30:49 +0000400 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
401 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 ++RenameCounter;
403 Changed = true;
404 }
405
406
407 // Loop over all external functions and globals. If we have two with
408 // identical names, merge them.
409 // FIXME: This code should disappear when we don't allow values with the same
410 // names when they have different types!
411 std::map<std::string, GlobalValue*> ExtSymbols;
412 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
413 Function *GV = I++;
414 if (GV->isDeclaration() && GV->hasName()) {
415 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
416 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
417 if (!X.second) {
418 // Found a conflict, replace this global with the previous one.
419 GlobalValue *OldGV = X.first->second;
420 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
421 GV->eraseFromParent();
422 Changed = true;
423 }
424 }
425 }
426 // Do the same for globals.
427 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
428 I != E;) {
429 GlobalVariable *GV = I++;
430 if (GV->isDeclaration() && GV->hasName()) {
431 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
432 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
433 if (!X.second) {
434 // Found a conflict, replace this global with the previous one.
435 GlobalValue *OldGV = X.first->second;
436 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
437 GV->eraseFromParent();
438 Changed = true;
439 }
440 }
441 }
442
443 return Changed;
444}
445
446/// printStructReturnPointerFunctionType - This is like printType for a struct
447/// return type, except, instead of printing the type as void (*)(Struct*, ...)
448/// print it as "Struct (*)(...)", for struct return functions.
David Greene302008d2009-07-14 20:18:05 +0000449void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
Devang Pateld222f862008-09-25 21:00:45 +0000450 const AttrListPtr &PAL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000451 const PointerType *TheTy) {
452 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
453 std::stringstream FunctionInnards;
454 FunctionInnards << " (*) (";
455 bool PrintedType = false;
456
457 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
458 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
459 unsigned Idx = 1;
Evan Cheng2054cb02008-01-11 03:07:46 +0000460 for (++I, ++Idx; I != E; ++I, ++Idx) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000461 if (PrintedType)
462 FunctionInnards << ", ";
Evan Cheng2054cb02008-01-11 03:07:46 +0000463 const Type *ArgTy = *I;
Devang Pateld222f862008-09-25 21:00:45 +0000464 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng17254e62008-01-11 09:12:49 +0000465 assert(isa<PointerType>(ArgTy));
466 ArgTy = cast<PointerType>(ArgTy)->getElementType();
467 }
Evan Cheng2054cb02008-01-11 03:07:46 +0000468 printType(FunctionInnards, ArgTy,
Devang Pateld222f862008-09-25 21:00:45 +0000469 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000470 PrintedType = true;
471 }
472 if (FTy->isVarArg()) {
473 if (PrintedType)
474 FunctionInnards << ", ...";
475 } else if (!PrintedType) {
476 FunctionInnards << "void";
477 }
478 FunctionInnards << ')';
479 std::string tstr = FunctionInnards.str();
480 printType(Out, RetTy,
Devang Pateld222f862008-09-25 21:00:45 +0000481 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000482}
483
Owen Anderson847b99b2008-08-21 00:14:44 +0000484raw_ostream &
David Greene302008d2009-07-14 20:18:05 +0000485CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
486 bool isSigned,
Owen Anderson847b99b2008-08-21 00:14:44 +0000487 const std::string &NameSoFar) {
488 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
489 "Invalid type for printSimpleType");
490 switch (Ty->getTypeID()) {
491 case Type::VoidTyID: return Out << "void " << NameSoFar;
492 case Type::IntegerTyID: {
493 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
494 if (NumBits == 1)
495 return Out << "bool " << NameSoFar;
496 else if (NumBits <= 8)
497 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
498 else if (NumBits <= 16)
499 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
500 else if (NumBits <= 32)
501 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
502 else if (NumBits <= 64)
503 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
504 else {
505 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
506 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
507 }
508 }
509 case Type::FloatTyID: return Out << "float " << NameSoFar;
510 case Type::DoubleTyID: return Out << "double " << NameSoFar;
511 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
512 // present matches host 'long double'.
513 case Type::X86_FP80TyID:
514 case Type::PPC_FP128TyID:
515 case Type::FP128TyID: return Out << "long double " << NameSoFar;
516
517 case Type::VectorTyID: {
518 const VectorType *VTy = cast<VectorType>(Ty);
519 return printSimpleType(Out, VTy->getElementType(), isSigned,
520 " __attribute__((vector_size(" +
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000521 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Owen Anderson847b99b2008-08-21 00:14:44 +0000522 }
523
524 default:
Edwin Török4d9756a2009-07-08 20:53:28 +0000525#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +0000526 errs() << "Unknown primitive type: " << *Ty << "\n";
Edwin Török4d9756a2009-07-08 20:53:28 +0000527#endif
Edwin Törökbd448e32009-07-14 16:55:14 +0000528 llvm_unreachable(0);
Owen Anderson847b99b2008-08-21 00:14:44 +0000529 }
530}
531
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532std::ostream &
533CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
Chris Lattnerd8090712008-03-02 03:41:23 +0000534 const std::string &NameSoFar) {
Chris Lattnerdb6d5ce2008-03-02 03:33:31 +0000535 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 "Invalid type for printSimpleType");
537 switch (Ty->getTypeID()) {
538 case Type::VoidTyID: return Out << "void " << NameSoFar;
539 case Type::IntegerTyID: {
540 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
541 if (NumBits == 1)
542 return Out << "bool " << NameSoFar;
543 else if (NumBits <= 8)
544 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
545 else if (NumBits <= 16)
546 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
547 else if (NumBits <= 32)
548 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
Dan Gohmana2245af2008-04-02 19:40:14 +0000549 else if (NumBits <= 64)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000550 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
Dan Gohmana2245af2008-04-02 19:40:14 +0000551 else {
552 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
553 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554 }
555 }
556 case Type::FloatTyID: return Out << "float " << NameSoFar;
557 case Type::DoubleTyID: return Out << "double " << NameSoFar;
Dale Johannesen137cef62007-09-17 00:38:27 +0000558 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
559 // present matches host 'long double'.
560 case Type::X86_FP80TyID:
561 case Type::PPC_FP128TyID:
562 case Type::FP128TyID: return Out << "long double " << NameSoFar;
Chris Lattnerdb6d5ce2008-03-02 03:33:31 +0000563
564 case Type::VectorTyID: {
565 const VectorType *VTy = cast<VectorType>(Ty);
Chris Lattnerd8090712008-03-02 03:41:23 +0000566 return printSimpleType(Out, VTy->getElementType(), isSigned,
Chris Lattnerfddca552008-03-02 03:39:43 +0000567 " __attribute__((vector_size(" +
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000568 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Chris Lattnerdb6d5ce2008-03-02 03:33:31 +0000569 }
570
571 default:
Edwin Török4d9756a2009-07-08 20:53:28 +0000572#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +0000573 errs() << "Unknown primitive type: " << *Ty << "\n";
Edwin Török4d9756a2009-07-08 20:53:28 +0000574#endif
Edwin Törökbd448e32009-07-14 16:55:14 +0000575 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000576 }
577}
578
579// Pass the Type* and the variable name and this prints out the variable
580// declaration.
581//
David Greene302008d2009-07-14 20:18:05 +0000582raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
583 const Type *Ty,
584 bool isSigned, const std::string &NameSoFar,
585 bool IgnoreName, const AttrListPtr &PAL) {
Owen Anderson847b99b2008-08-21 00:14:44 +0000586 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
587 printSimpleType(Out, Ty, isSigned, NameSoFar);
588 return Out;
589 }
590
591 // Check to see if the type is named.
592 if (!IgnoreName || isa<OpaqueType>(Ty)) {
593 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
594 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
595 }
596
597 switch (Ty->getTypeID()) {
598 case Type::FunctionTyID: {
599 const FunctionType *FTy = cast<FunctionType>(Ty);
600 std::stringstream FunctionInnards;
601 FunctionInnards << " (" << NameSoFar << ") (";
602 unsigned Idx = 1;
603 for (FunctionType::param_iterator I = FTy->param_begin(),
604 E = FTy->param_end(); I != E; ++I) {
605 const Type *ArgTy = *I;
Devang Pateld222f862008-09-25 21:00:45 +0000606 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Owen Anderson847b99b2008-08-21 00:14:44 +0000607 assert(isa<PointerType>(ArgTy));
608 ArgTy = cast<PointerType>(ArgTy)->getElementType();
609 }
610 if (I != FTy->param_begin())
611 FunctionInnards << ", ";
612 printType(FunctionInnards, ArgTy,
Devang Pateld222f862008-09-25 21:00:45 +0000613 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Owen Anderson847b99b2008-08-21 00:14:44 +0000614 ++Idx;
615 }
616 if (FTy->isVarArg()) {
617 if (FTy->getNumParams())
618 FunctionInnards << ", ...";
619 } else if (!FTy->getNumParams()) {
620 FunctionInnards << "void";
621 }
622 FunctionInnards << ')';
623 std::string tstr = FunctionInnards.str();
624 printType(Out, FTy->getReturnType(),
Devang Pateld222f862008-09-25 21:00:45 +0000625 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Owen Anderson847b99b2008-08-21 00:14:44 +0000626 return Out;
627 }
628 case Type::StructTyID: {
629 const StructType *STy = cast<StructType>(Ty);
630 Out << NameSoFar + " {\n";
631 unsigned Idx = 0;
632 for (StructType::element_iterator I = STy->element_begin(),
633 E = STy->element_end(); I != E; ++I) {
634 Out << " ";
635 printType(Out, *I, false, "field" + utostr(Idx++));
636 Out << ";\n";
637 }
638 Out << '}';
639 if (STy->isPacked())
640 Out << " __attribute__ ((packed))";
641 return Out;
642 }
643
644 case Type::PointerTyID: {
645 const PointerType *PTy = cast<PointerType>(Ty);
646 std::string ptrName = "*" + NameSoFar;
647
648 if (isa<ArrayType>(PTy->getElementType()) ||
649 isa<VectorType>(PTy->getElementType()))
650 ptrName = "(" + ptrName + ")";
651
652 if (!PAL.isEmpty())
653 // Must be a function ptr cast!
654 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
655 return printType(Out, PTy->getElementType(), false, ptrName);
656 }
657
658 case Type::ArrayTyID: {
659 const ArrayType *ATy = cast<ArrayType>(Ty);
660 unsigned NumElements = ATy->getNumElements();
661 if (NumElements == 0) NumElements = 1;
662 // Arrays are wrapped in structs to allow them to have normal
663 // value semantics (avoiding the array "decay").
664 Out << NameSoFar << " { ";
665 printType(Out, ATy->getElementType(), false,
666 "array[" + utostr(NumElements) + "]");
667 return Out << "; }";
668 }
669
670 case Type::OpaqueTyID: {
Owen Andersonde8a9442009-06-26 19:48:37 +0000671 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Owen Anderson847b99b2008-08-21 00:14:44 +0000672 assert(TypeNames.find(Ty) == TypeNames.end());
673 TypeNames[Ty] = TyName;
674 return Out << TyName << ' ' << NameSoFar;
675 }
676 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000677 llvm_unreachable("Unhandled case in getTypeProps!");
Owen Anderson847b99b2008-08-21 00:14:44 +0000678 }
679
680 return Out;
681}
682
683// Pass the Type* and the variable name and this prints out the variable
684// declaration.
685//
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
687 bool isSigned, const std::string &NameSoFar,
Devang Pateld222f862008-09-25 21:00:45 +0000688 bool IgnoreName, const AttrListPtr &PAL) {
Chris Lattnerdb6d5ce2008-03-02 03:33:31 +0000689 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690 printSimpleType(Out, Ty, isSigned, NameSoFar);
691 return Out;
692 }
693
694 // Check to see if the type is named.
695 if (!IgnoreName || isa<OpaqueType>(Ty)) {
696 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
697 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
698 }
699
700 switch (Ty->getTypeID()) {
701 case Type::FunctionTyID: {
702 const FunctionType *FTy = cast<FunctionType>(Ty);
703 std::stringstream FunctionInnards;
704 FunctionInnards << " (" << NameSoFar << ") (";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705 unsigned Idx = 1;
706 for (FunctionType::param_iterator I = FTy->param_begin(),
707 E = FTy->param_end(); I != E; ++I) {
Evan Chengb8a072c2008-01-12 18:53:07 +0000708 const Type *ArgTy = *I;
Devang Pateld222f862008-09-25 21:00:45 +0000709 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Chengb8a072c2008-01-12 18:53:07 +0000710 assert(isa<PointerType>(ArgTy));
711 ArgTy = cast<PointerType>(ArgTy)->getElementType();
712 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000713 if (I != FTy->param_begin())
714 FunctionInnards << ", ";
Evan Chengb8a072c2008-01-12 18:53:07 +0000715 printType(FunctionInnards, ArgTy,
Devang Pateld222f862008-09-25 21:00:45 +0000716 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717 ++Idx;
718 }
719 if (FTy->isVarArg()) {
720 if (FTy->getNumParams())
721 FunctionInnards << ", ...";
722 } else if (!FTy->getNumParams()) {
723 FunctionInnards << "void";
724 }
725 FunctionInnards << ')';
726 std::string tstr = FunctionInnards.str();
727 printType(Out, FTy->getReturnType(),
Devang Pateld222f862008-09-25 21:00:45 +0000728 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000729 return Out;
730 }
731 case Type::StructTyID: {
732 const StructType *STy = cast<StructType>(Ty);
733 Out << NameSoFar + " {\n";
734 unsigned Idx = 0;
735 for (StructType::element_iterator I = STy->element_begin(),
736 E = STy->element_end(); I != E; ++I) {
737 Out << " ";
738 printType(Out, *I, false, "field" + utostr(Idx++));
739 Out << ";\n";
740 }
741 Out << '}';
742 if (STy->isPacked())
743 Out << " __attribute__ ((packed))";
744 return Out;
745 }
746
747 case Type::PointerTyID: {
748 const PointerType *PTy = cast<PointerType>(Ty);
749 std::string ptrName = "*" + NameSoFar;
750
751 if (isa<ArrayType>(PTy->getElementType()) ||
752 isa<VectorType>(PTy->getElementType()))
753 ptrName = "(" + ptrName + ")";
754
Chris Lattner1c8733e2008-03-12 17:45:29 +0000755 if (!PAL.isEmpty())
Evan Chengb8a072c2008-01-12 18:53:07 +0000756 // Must be a function ptr cast!
757 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758 return printType(Out, PTy->getElementType(), false, ptrName);
759 }
760
761 case Type::ArrayTyID: {
762 const ArrayType *ATy = cast<ArrayType>(Ty);
763 unsigned NumElements = ATy->getNumElements();
764 if (NumElements == 0) NumElements = 1;
Dan Gohman5d995b02008-06-02 21:30:49 +0000765 // Arrays are wrapped in structs to allow them to have normal
766 // value semantics (avoiding the array "decay").
767 Out << NameSoFar << " { ";
768 printType(Out, ATy->getElementType(), false,
769 "array[" + utostr(NumElements) + "]");
770 return Out << "; }";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000771 }
772
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773 case Type::OpaqueTyID: {
Owen Andersonde8a9442009-06-26 19:48:37 +0000774 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000775 assert(TypeNames.find(Ty) == TypeNames.end());
776 TypeNames[Ty] = TyName;
777 return Out << TyName << ' ' << NameSoFar;
778 }
779 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000780 llvm_unreachable("Unhandled case in getTypeProps!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000781 }
782
783 return Out;
784}
785
Dan Gohmanad831302008-07-24 17:57:48 +0000786void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787
788 // As a special case, print the array as a string if it is an array of
789 // ubytes or an array of sbytes with positive values.
790 //
791 const Type *ETy = CPA->getType()->getElementType();
Owen Anderson35b47072009-08-13 21:58:54 +0000792 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
793 ETy == Type::getInt8Ty(CPA->getContext()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000794
795 // Make sure the last character is a null char, as automatically added by C
796 if (isString && (CPA->getNumOperands() == 0 ||
797 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
798 isString = false;
799
800 if (isString) {
801 Out << '\"';
802 // Keep track of whether the last number was a hexadecimal escape
803 bool LastWasHex = false;
804
805 // Do not include the last character, which we know is null
806 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
807 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
808
809 // Print it out literally if it is a printable character. The only thing
810 // to be careful about is when the last letter output was a hex escape
811 // code, in which case we have to be careful not to print out hex digits
812 // explicitly (the C compiler thinks it is a continuation of the previous
813 // character, sheesh...)
814 //
815 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
816 LastWasHex = false;
817 if (C == '"' || C == '\\')
Chris Lattner009f3962008-08-21 05:51:43 +0000818 Out << "\\" << (char)C;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819 else
Chris Lattner009f3962008-08-21 05:51:43 +0000820 Out << (char)C;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000821 } else {
822 LastWasHex = false;
823 switch (C) {
824 case '\n': Out << "\\n"; break;
825 case '\t': Out << "\\t"; break;
826 case '\r': Out << "\\r"; break;
827 case '\v': Out << "\\v"; break;
828 case '\a': Out << "\\a"; break;
829 case '\"': Out << "\\\""; break;
830 case '\'': Out << "\\\'"; break;
831 default:
832 Out << "\\x";
833 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
834 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
835 LastWasHex = true;
836 break;
837 }
838 }
839 }
840 Out << '\"';
841 } else {
842 Out << '{';
843 if (CPA->getNumOperands()) {
844 Out << ' ';
Dan Gohmanad831302008-07-24 17:57:48 +0000845 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000846 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
847 Out << ", ";
Dan Gohmanad831302008-07-24 17:57:48 +0000848 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 }
850 }
851 Out << " }";
852 }
853}
854
Dan Gohmanad831302008-07-24 17:57:48 +0000855void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000856 Out << '{';
857 if (CP->getNumOperands()) {
858 Out << ' ';
Dan Gohmanad831302008-07-24 17:57:48 +0000859 printConstant(cast<Constant>(CP->getOperand(0)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000860 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
861 Out << ", ";
Dan Gohmanad831302008-07-24 17:57:48 +0000862 printConstant(cast<Constant>(CP->getOperand(i)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000863 }
864 }
865 Out << " }";
866}
867
868// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
869// textually as a double (rather than as a reference to a stack-allocated
870// variable). We decide this by converting CFP to a string and back into a
871// double, and then checking whether the conversion results in a bit-equal
872// double to the original value of CFP. This depends on us and the target C
873// compiler agreeing on the conversion process (which is pretty likely since we
874// only deal in IEEE FP).
875//
876static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Dale Johannesen6e547b42008-10-09 23:00:39 +0000877 bool ignored;
Dale Johannesen137cef62007-09-17 00:38:27 +0000878 // Do long doubles in hex for now.
Owen Anderson35b47072009-08-13 21:58:54 +0000879 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
880 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
Dale Johannesen2fc20782007-09-14 22:26:36 +0000881 return false;
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000882 APFloat APF = APFloat(CFP->getValueAPF()); // copy
Owen Anderson35b47072009-08-13 21:58:54 +0000883 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
Dale Johannesen6e547b42008-10-09 23:00:39 +0000884 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000885#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
886 char Buffer[100];
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000887 sprintf(Buffer, "%a", APF.convertToDouble());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000888 if (!strncmp(Buffer, "0x", 2) ||
889 !strncmp(Buffer, "-0x", 3) ||
890 !strncmp(Buffer, "+0x", 3))
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000891 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 return false;
893#else
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000894 std::string StrVal = ftostr(APF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000895
896 while (StrVal[0] == ' ')
897 StrVal.erase(StrVal.begin());
898
899 // Check to make sure that the stringized number is not some string like "Inf"
900 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
901 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
902 ((StrVal[0] == '-' || StrVal[0] == '+') &&
903 (StrVal[1] >= '0' && StrVal[1] <= '9')))
904 // Reparse stringized version!
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000905 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000906 return false;
907#endif
908}
909
910/// Print out the casting for a cast operation. This does the double casting
911/// necessary for conversion to the destination type, if necessary.
912/// @brief Print a cast
913void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
914 // Print the destination type cast
915 switch (opc) {
916 case Instruction::UIToFP:
917 case Instruction::SIToFP:
918 case Instruction::IntToPtr:
919 case Instruction::Trunc:
920 case Instruction::BitCast:
921 case Instruction::FPExt:
922 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
923 Out << '(';
924 printType(Out, DstTy);
925 Out << ')';
926 break;
927 case Instruction::ZExt:
928 case Instruction::PtrToInt:
929 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
930 Out << '(';
931 printSimpleType(Out, DstTy, false);
932 Out << ')';
933 break;
934 case Instruction::SExt:
935 case Instruction::FPToSI: // For these, make sure we get a signed dest
936 Out << '(';
937 printSimpleType(Out, DstTy, true);
938 Out << ')';
939 break;
940 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000941 llvm_unreachable("Invalid cast opcode");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942 }
943
944 // Print the source type cast
945 switch (opc) {
946 case Instruction::UIToFP:
947 case Instruction::ZExt:
948 Out << '(';
949 printSimpleType(Out, SrcTy, false);
950 Out << ')';
951 break;
952 case Instruction::SIToFP:
953 case Instruction::SExt:
954 Out << '(';
955 printSimpleType(Out, SrcTy, true);
956 Out << ')';
957 break;
958 case Instruction::IntToPtr:
959 case Instruction::PtrToInt:
960 // Avoid "cast to pointer from integer of different size" warnings
961 Out << "(unsigned long)";
962 break;
963 case Instruction::Trunc:
964 case Instruction::BitCast:
965 case Instruction::FPExt:
966 case Instruction::FPTrunc:
967 case Instruction::FPToSI:
968 case Instruction::FPToUI:
969 break; // These don't need a source cast.
970 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000971 llvm_unreachable("Invalid cast opcode");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972 break;
973 }
974}
975
976// printConstant - The LLVM Constant to C Constant converter.
Dan Gohmanad831302008-07-24 17:57:48 +0000977void CWriter::printConstant(Constant *CPV, bool Static) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000978 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
979 switch (CE->getOpcode()) {
980 case Instruction::Trunc:
981 case Instruction::ZExt:
982 case Instruction::SExt:
983 case Instruction::FPTrunc:
984 case Instruction::FPExt:
985 case Instruction::UIToFP:
986 case Instruction::SIToFP:
987 case Instruction::FPToUI:
988 case Instruction::FPToSI:
989 case Instruction::PtrToInt:
990 case Instruction::IntToPtr:
991 case Instruction::BitCast:
992 Out << "(";
993 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
994 if (CE->getOpcode() == Instruction::SExt &&
Owen Anderson35b47072009-08-13 21:58:54 +0000995 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996 // Make sure we really sext from bool here by subtracting from 0
997 Out << "0-";
998 }
Dan Gohmanad831302008-07-24 17:57:48 +0000999 printConstant(CE->getOperand(0), Static);
Owen Anderson35b47072009-08-13 21:58:54 +00001000 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001001 (CE->getOpcode() == Instruction::Trunc ||
1002 CE->getOpcode() == Instruction::FPToUI ||
1003 CE->getOpcode() == Instruction::FPToSI ||
1004 CE->getOpcode() == Instruction::PtrToInt)) {
1005 // Make sure we really truncate to bool here by anding with 1
1006 Out << "&1u";
1007 }
1008 Out << ')';
1009 return;
1010
1011 case Instruction::GetElementPtr:
Chris Lattner8bbc8592008-03-02 08:07:24 +00001012 Out << "(";
1013 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
Dan Gohmanad831302008-07-24 17:57:48 +00001014 gep_type_end(CPV), Static);
Chris Lattner8bbc8592008-03-02 08:07:24 +00001015 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001016 return;
1017 case Instruction::Select:
1018 Out << '(';
Dan Gohmanad831302008-07-24 17:57:48 +00001019 printConstant(CE->getOperand(0), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020 Out << '?';
Dan Gohmanad831302008-07-24 17:57:48 +00001021 printConstant(CE->getOperand(1), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001022 Out << ':';
Dan Gohmanad831302008-07-24 17:57:48 +00001023 printConstant(CE->getOperand(2), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001024 Out << ')';
1025 return;
1026 case Instruction::Add:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001027 case Instruction::FAdd:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028 case Instruction::Sub:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001029 case Instruction::FSub:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001030 case Instruction::Mul:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001031 case Instruction::FMul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001032 case Instruction::SDiv:
1033 case Instruction::UDiv:
1034 case Instruction::FDiv:
1035 case Instruction::URem:
1036 case Instruction::SRem:
1037 case Instruction::FRem:
1038 case Instruction::And:
1039 case Instruction::Or:
1040 case Instruction::Xor:
1041 case Instruction::ICmp:
1042 case Instruction::Shl:
1043 case Instruction::LShr:
1044 case Instruction::AShr:
1045 {
1046 Out << '(';
Dan Gohmanad831302008-07-24 17:57:48 +00001047 bool NeedsClosingParens = printConstExprCast(CE, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1049 switch (CE->getOpcode()) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00001050 case Instruction::Add:
1051 case Instruction::FAdd: Out << " + "; break;
1052 case Instruction::Sub:
1053 case Instruction::FSub: Out << " - "; break;
1054 case Instruction::Mul:
1055 case Instruction::FMul: Out << " * "; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001056 case Instruction::URem:
1057 case Instruction::SRem:
1058 case Instruction::FRem: Out << " % "; break;
1059 case Instruction::UDiv:
1060 case Instruction::SDiv:
1061 case Instruction::FDiv: Out << " / "; break;
1062 case Instruction::And: Out << " & "; break;
1063 case Instruction::Or: Out << " | "; break;
1064 case Instruction::Xor: Out << " ^ "; break;
1065 case Instruction::Shl: Out << " << "; break;
1066 case Instruction::LShr:
1067 case Instruction::AShr: Out << " >> "; break;
1068 case Instruction::ICmp:
1069 switch (CE->getPredicate()) {
1070 case ICmpInst::ICMP_EQ: Out << " == "; break;
1071 case ICmpInst::ICMP_NE: Out << " != "; break;
1072 case ICmpInst::ICMP_SLT:
1073 case ICmpInst::ICMP_ULT: Out << " < "; break;
1074 case ICmpInst::ICMP_SLE:
1075 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1076 case ICmpInst::ICMP_SGT:
1077 case ICmpInst::ICMP_UGT: Out << " > "; break;
1078 case ICmpInst::ICMP_SGE:
1079 case ICmpInst::ICMP_UGE: Out << " >= "; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00001080 default: llvm_unreachable("Illegal ICmp predicate");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001081 }
1082 break;
Edwin Törökbd448e32009-07-14 16:55:14 +00001083 default: llvm_unreachable("Illegal opcode here!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001084 }
1085 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1086 if (NeedsClosingParens)
1087 Out << "))";
1088 Out << ')';
1089 return;
1090 }
1091 case Instruction::FCmp: {
1092 Out << '(';
Dan Gohmanad831302008-07-24 17:57:48 +00001093 bool NeedsClosingParens = printConstExprCast(CE, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1095 Out << "0";
1096 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1097 Out << "1";
1098 else {
1099 const char* op = 0;
1100 switch (CE->getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001101 default: llvm_unreachable("Illegal FCmp predicate");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001102 case FCmpInst::FCMP_ORD: op = "ord"; break;
1103 case FCmpInst::FCMP_UNO: op = "uno"; break;
1104 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1105 case FCmpInst::FCMP_UNE: op = "une"; break;
1106 case FCmpInst::FCMP_ULT: op = "ult"; break;
1107 case FCmpInst::FCMP_ULE: op = "ule"; break;
1108 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1109 case FCmpInst::FCMP_UGE: op = "uge"; break;
1110 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1111 case FCmpInst::FCMP_ONE: op = "one"; break;
1112 case FCmpInst::FCMP_OLT: op = "olt"; break;
1113 case FCmpInst::FCMP_OLE: op = "ole"; break;
1114 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1115 case FCmpInst::FCMP_OGE: op = "oge"; break;
1116 }
1117 Out << "llvm_fcmp_" << op << "(";
1118 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1119 Out << ", ";
1120 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1121 Out << ")";
1122 }
1123 if (NeedsClosingParens)
1124 Out << "))";
1125 Out << ')';
Anton Korobeynikov44891ce2007-12-21 23:33:44 +00001126 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001127 }
1128 default:
Edwin Török4d9756a2009-07-08 20:53:28 +00001129#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +00001130 errs() << "CWriter Error: Unhandled constant expression: "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001131 << *CE << "\n";
Edwin Török4d9756a2009-07-08 20:53:28 +00001132#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001133 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001134 }
Dan Gohman76c2cb42008-05-23 16:57:00 +00001135 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001136 Out << "((";
1137 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnerc72d9e32008-03-02 08:14:45 +00001138 Out << ")/*UNDEF*/";
1139 if (!isa<VectorType>(CPV->getType())) {
1140 Out << "0)";
1141 } else {
1142 Out << "{})";
1143 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001144 return;
1145 }
1146
1147 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1148 const Type* Ty = CI->getType();
Owen Anderson35b47072009-08-13 21:58:54 +00001149 if (Ty == Type::getInt1Ty(CPV->getContext()))
Chris Lattner63fb1f02008-03-02 03:16:38 +00001150 Out << (CI->getZExtValue() ? '1' : '0');
Owen Anderson35b47072009-08-13 21:58:54 +00001151 else if (Ty == Type::getInt32Ty(CPV->getContext()))
Chris Lattner63fb1f02008-03-02 03:16:38 +00001152 Out << CI->getZExtValue() << 'u';
1153 else if (Ty->getPrimitiveSizeInBits() > 32)
1154 Out << CI->getZExtValue() << "ull";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001155 else {
1156 Out << "((";
1157 printSimpleType(Out, Ty, false) << ')';
1158 if (CI->isMinValue(true))
1159 Out << CI->getZExtValue() << 'u';
1160 else
1161 Out << CI->getSExtValue();
Dale Johannesen8830f922009-05-19 00:46:42 +00001162 Out << ')';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163 }
1164 return;
1165 }
1166
1167 switch (CPV->getType()->getTypeID()) {
1168 case Type::FloatTyID:
Dale Johannesen137cef62007-09-17 00:38:27 +00001169 case Type::DoubleTyID:
1170 case Type::X86_FP80TyID:
1171 case Type::PPC_FP128TyID:
1172 case Type::FP128TyID: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001173 ConstantFP *FPC = cast<ConstantFP>(CPV);
1174 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
1175 if (I != FPConstantMap.end()) {
1176 // Because of FP precision problems we must load from a stack allocated
1177 // value that holds the value in hex.
Owen Anderson35b47072009-08-13 21:58:54 +00001178 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
1179 "float" :
1180 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
1181 "double" :
Dale Johannesen137cef62007-09-17 00:38:27 +00001182 "long double")
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001183 << "*)&FPConstant" << I->second << ')';
1184 } else {
Chris Lattnera68e3512008-10-17 06:11:48 +00001185 double V;
Owen Anderson35b47072009-08-13 21:58:54 +00001186 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
Chris Lattnera68e3512008-10-17 06:11:48 +00001187 V = FPC->getValueAPF().convertToFloat();
Owen Anderson35b47072009-08-13 21:58:54 +00001188 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
Chris Lattnera68e3512008-10-17 06:11:48 +00001189 V = FPC->getValueAPF().convertToDouble();
1190 else {
1191 // Long double. Convert the number to double, discarding precision.
1192 // This is not awesome, but it at least makes the CBE output somewhat
1193 // useful.
1194 APFloat Tmp = FPC->getValueAPF();
1195 bool LosesInfo;
1196 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1197 V = Tmp.convertToDouble();
1198 }
1199
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001200 if (IsNAN(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201 // The value is NaN
1202
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001203 // FIXME the actual NaN bits should be emitted.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1205 // it's 0x7ff4.
1206 const unsigned long QuietNaN = 0x7ff8UL;
1207 //const unsigned long SignalNaN = 0x7ff4UL;
1208
1209 // We need to grab the first part of the FP #
1210 char Buffer[100];
1211
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001212 uint64_t ll = DoubleToBits(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001213 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
1214
1215 std::string Num(&Buffer[0], &Buffer[6]);
1216 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1217
Owen Anderson35b47072009-08-13 21:58:54 +00001218 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001219 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1220 << Buffer << "\") /*nan*/ ";
1221 else
1222 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1223 << Buffer << "\") /*nan*/ ";
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001224 } else if (IsInf(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001225 // The value is Inf
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001226 if (V < 0) Out << '-';
Owen Anderson35b47072009-08-13 21:58:54 +00001227 Out << "LLVM_INF" <<
1228 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001229 << " /*inf*/ ";
1230 } else {
1231 std::string Num;
1232#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1233 // Print out the constant as a floating point number.
1234 char Buffer[100];
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001235 sprintf(Buffer, "%a", V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001236 Num = Buffer;
1237#else
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001238 Num = ftostr(FPC->getValueAPF());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001239#endif
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001240 Out << Num;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001241 }
1242 }
1243 break;
1244 }
1245
1246 case Type::ArrayTyID:
Dan Gohman29b19472008-07-23 18:41:03 +00001247 // Use C99 compound expression literal initializer syntax.
Dan Gohmanad831302008-07-24 17:57:48 +00001248 if (!Static) {
1249 Out << "(";
1250 printType(Out, CPV->getType());
1251 Out << ")";
1252 }
Dan Gohman5d995b02008-06-02 21:30:49 +00001253 Out << "{ "; // Arrays are wrapped in struct types.
Chris Lattner8673e322008-03-02 05:46:57 +00001254 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
Dan Gohmanad831302008-07-24 17:57:48 +00001255 printConstantArray(CA, Static);
Chris Lattner63fb1f02008-03-02 03:16:38 +00001256 } else {
1257 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258 const ArrayType *AT = cast<ArrayType>(CPV->getType());
1259 Out << '{';
1260 if (AT->getNumElements()) {
1261 Out << ' ';
Owen Andersonaac28372009-07-31 20:28:14 +00001262 Constant *CZ = Constant::getNullValue(AT->getElementType());
Dan Gohmanad831302008-07-24 17:57:48 +00001263 printConstant(CZ, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1265 Out << ", ";
Dan Gohmanad831302008-07-24 17:57:48 +00001266 printConstant(CZ, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 }
1268 }
1269 Out << " }";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 }
Dan Gohman5d995b02008-06-02 21:30:49 +00001271 Out << " }"; // Arrays are wrapped in struct types.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001272 break;
1273
1274 case Type::VectorTyID:
Chris Lattner70f0f672008-03-02 03:29:50 +00001275 // Use C99 compound expression literal initializer syntax.
Dan Gohmanad831302008-07-24 17:57:48 +00001276 if (!Static) {
1277 Out << "(";
1278 printType(Out, CPV->getType());
1279 Out << ")";
1280 }
Chris Lattner8673e322008-03-02 05:46:57 +00001281 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
Dan Gohmanad831302008-07-24 17:57:48 +00001282 printConstantVector(CV, Static);
Chris Lattner63fb1f02008-03-02 03:16:38 +00001283 } else {
1284 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1285 const VectorType *VT = cast<VectorType>(CPV->getType());
1286 Out << "{ ";
Owen Andersonaac28372009-07-31 20:28:14 +00001287 Constant *CZ = Constant::getNullValue(VT->getElementType());
Dan Gohmanad831302008-07-24 17:57:48 +00001288 printConstant(CZ, Static);
Chris Lattner6d4cd9b2008-03-02 03:18:46 +00001289 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
Chris Lattner63fb1f02008-03-02 03:16:38 +00001290 Out << ", ";
Dan Gohmanad831302008-07-24 17:57:48 +00001291 printConstant(CZ, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 }
1293 Out << " }";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294 }
1295 break;
1296
1297 case Type::StructTyID:
Dan Gohman29b19472008-07-23 18:41:03 +00001298 // Use C99 compound expression literal initializer syntax.
Dan Gohmanad831302008-07-24 17:57:48 +00001299 if (!Static) {
1300 Out << "(";
1301 printType(Out, CPV->getType());
1302 Out << ")";
1303 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001304 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1305 const StructType *ST = cast<StructType>(CPV->getType());
1306 Out << '{';
1307 if (ST->getNumElements()) {
1308 Out << ' ';
Owen Andersonaac28372009-07-31 20:28:14 +00001309 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001310 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1311 Out << ", ";
Owen Andersonaac28372009-07-31 20:28:14 +00001312 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001313 }
1314 }
1315 Out << " }";
1316 } else {
1317 Out << '{';
1318 if (CPV->getNumOperands()) {
1319 Out << ' ';
Dan Gohmanad831302008-07-24 17:57:48 +00001320 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1322 Out << ", ";
Dan Gohmanad831302008-07-24 17:57:48 +00001323 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 }
1325 }
1326 Out << " }";
1327 }
1328 break;
1329
1330 case Type::PointerTyID:
1331 if (isa<ConstantPointerNull>(CPV)) {
1332 Out << "((";
1333 printType(Out, CPV->getType()); // sign doesn't matter
1334 Out << ")/*NULL*/0)";
1335 break;
1336 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
Dan Gohmanad831302008-07-24 17:57:48 +00001337 writeOperand(GV, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001338 break;
1339 }
1340 // FALL THROUGH
1341 default:
Edwin Török4d9756a2009-07-08 20:53:28 +00001342#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +00001343 errs() << "Unknown constant type: " << *CPV << "\n";
Edwin Török4d9756a2009-07-08 20:53:28 +00001344#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001345 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001346 }
1347}
1348
1349// Some constant expressions need to be casted back to the original types
1350// because their operands were casted to the expected type. This function takes
1351// care of detecting that case and printing the cast for the ConstantExpr.
Dan Gohmanad831302008-07-24 17:57:48 +00001352bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001353 bool NeedsExplicitCast = false;
1354 const Type *Ty = CE->getOperand(0)->getType();
1355 bool TypeIsSigned = false;
1356 switch (CE->getOpcode()) {
Dan Gohmane1790de2008-07-18 18:43:12 +00001357 case Instruction::Add:
1358 case Instruction::Sub:
1359 case Instruction::Mul:
1360 // We need to cast integer arithmetic so that it is always performed
1361 // as unsigned, to avoid undefined behavior on overflow.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001362 case Instruction::LShr:
1363 case Instruction::URem:
1364 case Instruction::UDiv: NeedsExplicitCast = true; break;
1365 case Instruction::AShr:
1366 case Instruction::SRem:
1367 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1368 case Instruction::SExt:
1369 Ty = CE->getType();
1370 NeedsExplicitCast = true;
1371 TypeIsSigned = true;
1372 break;
1373 case Instruction::ZExt:
1374 case Instruction::Trunc:
1375 case Instruction::FPTrunc:
1376 case Instruction::FPExt:
1377 case Instruction::UIToFP:
1378 case Instruction::SIToFP:
1379 case Instruction::FPToUI:
1380 case Instruction::FPToSI:
1381 case Instruction::PtrToInt:
1382 case Instruction::IntToPtr:
1383 case Instruction::BitCast:
1384 Ty = CE->getType();
1385 NeedsExplicitCast = true;
1386 break;
1387 default: break;
1388 }
1389 if (NeedsExplicitCast) {
1390 Out << "((";
Owen Anderson35b47072009-08-13 21:58:54 +00001391 if (Ty->isInteger() && Ty != Type::getInt1Ty(Ty->getContext()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001392 printSimpleType(Out, Ty, TypeIsSigned);
1393 else
1394 printType(Out, Ty); // not integer, sign doesn't matter
1395 Out << ")(";
1396 }
1397 return NeedsExplicitCast;
1398}
1399
1400// Print a constant assuming that it is the operand for a given Opcode. The
1401// opcodes that care about sign need to cast their operands to the expected
1402// type before the operation proceeds. This function does the casting.
1403void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1404
1405 // Extract the operand's type, we'll need it.
1406 const Type* OpTy = CPV->getType();
1407
1408 // Indicate whether to do the cast or not.
1409 bool shouldCast = false;
1410 bool typeIsSigned = false;
1411
1412 // Based on the Opcode for which this Constant is being written, determine
1413 // the new type to which the operand should be casted by setting the value
1414 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1415 // casted below.
1416 switch (Opcode) {
1417 default:
1418 // for most instructions, it doesn't matter
1419 break;
Dan Gohmane1790de2008-07-18 18:43:12 +00001420 case Instruction::Add:
1421 case Instruction::Sub:
1422 case Instruction::Mul:
1423 // We need to cast integer arithmetic so that it is always performed
1424 // as unsigned, to avoid undefined behavior on overflow.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001425 case Instruction::LShr:
1426 case Instruction::UDiv:
1427 case Instruction::URem:
1428 shouldCast = true;
1429 break;
1430 case Instruction::AShr:
1431 case Instruction::SDiv:
1432 case Instruction::SRem:
1433 shouldCast = true;
1434 typeIsSigned = true;
1435 break;
1436 }
1437
1438 // Write out the casted constant if we should, otherwise just write the
1439 // operand.
1440 if (shouldCast) {
1441 Out << "((";
1442 printSimpleType(Out, OpTy, typeIsSigned);
1443 Out << ")";
Dan Gohmanad831302008-07-24 17:57:48 +00001444 printConstant(CPV, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001445 Out << ")";
1446 } else
Dan Gohmanad831302008-07-24 17:57:48 +00001447 printConstant(CPV, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001448}
1449
1450std::string CWriter::GetValueName(const Value *Operand) {
Chris Lattnerb66867f2009-07-13 23:46:46 +00001451 // Mangle globals with the standard mangler interface for LLC compatibility.
Chris Lattnerd2f59b82010-01-13 19:54:07 +00001452 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand)) {
1453 SmallString<128> Str;
1454 Mang->getNameWithPrefix(Str, GV, false);
1455 return Mangle(Str.str().str());
1456 }
Chris Lattnerb66867f2009-07-13 23:46:46 +00001457
1458 std::string Name = Operand->getName();
1459
1460 if (Name.empty()) { // Assign unique names to local temporaries.
1461 unsigned &No = AnonValueNumbers[Operand];
1462 if (No == 0)
1463 No = ++NextAnonValueNumber;
1464 Name = "tmp__" + utostr(No);
1465 }
1466
1467 std::string VarName;
1468 VarName.reserve(Name.capacity());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001469
Chris Lattnerb66867f2009-07-13 23:46:46 +00001470 for (std::string::iterator I = Name.begin(), E = Name.end();
1471 I != E; ++I) {
1472 char ch = *I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001473
Chris Lattnerb66867f2009-07-13 23:46:46 +00001474 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1475 (ch >= '0' && ch <= '9') || ch == '_')) {
1476 char buffer[5];
1477 sprintf(buffer, "_%x_", ch);
1478 VarName += buffer;
1479 } else
1480 VarName += ch;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001481 }
1482
Chris Lattnerb66867f2009-07-13 23:46:46 +00001483 return "llvm_cbe_" + VarName;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001484}
1485
Chris Lattnerd70f5a82008-05-31 09:23:55 +00001486/// writeInstComputationInline - Emit the computation for the specified
1487/// instruction inline, with no destination provided.
1488void CWriter::writeInstComputationInline(Instruction &I) {
Dale Johannesen787881e2009-06-18 01:07:23 +00001489 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1490 // Validate this.
1491 const Type *Ty = I.getType();
Owen Anderson35b47072009-08-13 21:58:54 +00001492 if (Ty->isInteger() && (Ty!=Type::getInt1Ty(I.getContext()) &&
1493 Ty!=Type::getInt8Ty(I.getContext()) &&
1494 Ty!=Type::getInt16Ty(I.getContext()) &&
1495 Ty!=Type::getInt32Ty(I.getContext()) &&
1496 Ty!=Type::getInt64Ty(I.getContext()))) {
Edwin Török4d9756a2009-07-08 20:53:28 +00001497 llvm_report_error("The C backend does not currently support integer "
1498 "types of widths other than 1, 8, 16, 32, 64.\n"
1499 "This is being tracked as PR 4158.");
Dale Johannesen787881e2009-06-18 01:07:23 +00001500 }
1501
Chris Lattnerd70f5a82008-05-31 09:23:55 +00001502 // If this is a non-trivial bool computation, make sure to truncate down to
1503 // a 1 bit value. This is important because we want "add i1 x, y" to return
1504 // "0" when x and y are true, not "2" for example.
1505 bool NeedBoolTrunc = false;
Owen Anderson35b47072009-08-13 21:58:54 +00001506 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1507 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
Chris Lattnerd70f5a82008-05-31 09:23:55 +00001508 NeedBoolTrunc = true;
1509
1510 if (NeedBoolTrunc)
1511 Out << "((";
1512
1513 visit(I);
1514
1515 if (NeedBoolTrunc)
1516 Out << ")&1)";
1517}
1518
1519
Dan Gohmanad831302008-07-24 17:57:48 +00001520void CWriter::writeOperandInternal(Value *Operand, bool Static) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnerd70f5a82008-05-31 09:23:55 +00001522 // Should we inline this instruction to build a tree?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001523 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001524 Out << '(';
Chris Lattnerd70f5a82008-05-31 09:23:55 +00001525 writeInstComputationInline(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001526 Out << ')';
1527 return;
1528 }
1529
1530 Constant* CPV = dyn_cast<Constant>(Operand);
1531
1532 if (CPV && !isa<GlobalValue>(CPV))
Dan Gohmanad831302008-07-24 17:57:48 +00001533 printConstant(CPV, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001534 else
1535 Out << GetValueName(Operand);
1536}
1537
Dan Gohmanad831302008-07-24 17:57:48 +00001538void CWriter::writeOperand(Value *Operand, bool Static) {
Chris Lattner8bbc8592008-03-02 08:07:24 +00001539 bool isAddressImplicit = isAddressExposed(Operand);
1540 if (isAddressImplicit)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001541 Out << "(&"; // Global variables are referenced as their addresses by llvm
1542
Dan Gohmanad831302008-07-24 17:57:48 +00001543 writeOperandInternal(Operand, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001544
Chris Lattner8bbc8592008-03-02 08:07:24 +00001545 if (isAddressImplicit)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001546 Out << ')';
1547}
1548
1549// Some instructions need to have their result value casted back to the
1550// original types because their operands were casted to the expected type.
1551// This function takes care of detecting that case and printing the cast
1552// for the Instruction.
1553bool CWriter::writeInstructionCast(const Instruction &I) {
1554 const Type *Ty = I.getOperand(0)->getType();
1555 switch (I.getOpcode()) {
Dan Gohmane1790de2008-07-18 18:43:12 +00001556 case Instruction::Add:
1557 case Instruction::Sub:
1558 case Instruction::Mul:
1559 // We need to cast integer arithmetic so that it is always performed
1560 // as unsigned, to avoid undefined behavior on overflow.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001561 case Instruction::LShr:
1562 case Instruction::URem:
1563 case Instruction::UDiv:
1564 Out << "((";
1565 printSimpleType(Out, Ty, false);
1566 Out << ")(";
1567 return true;
1568 case Instruction::AShr:
1569 case Instruction::SRem:
1570 case Instruction::SDiv:
1571 Out << "((";
1572 printSimpleType(Out, Ty, true);
1573 Out << ")(";
1574 return true;
1575 default: break;
1576 }
1577 return false;
1578}
1579
1580// Write the operand with a cast to another type based on the Opcode being used.
1581// This will be used in cases where an instruction has specific type
1582// requirements (usually signedness) for its operands.
1583void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1584
1585 // Extract the operand's type, we'll need it.
1586 const Type* OpTy = Operand->getType();
1587
1588 // Indicate whether to do the cast or not.
1589 bool shouldCast = false;
1590
1591 // Indicate whether the cast should be to a signed type or not.
1592 bool castIsSigned = false;
1593
1594 // Based on the Opcode for which this Operand is being written, determine
1595 // the new type to which the operand should be casted by setting the value
1596 // of OpTy. If we change OpTy, also set shouldCast to true.
1597 switch (Opcode) {
1598 default:
1599 // for most instructions, it doesn't matter
1600 break;
Dan Gohmane1790de2008-07-18 18:43:12 +00001601 case Instruction::Add:
1602 case Instruction::Sub:
1603 case Instruction::Mul:
1604 // We need to cast integer arithmetic so that it is always performed
1605 // as unsigned, to avoid undefined behavior on overflow.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001606 case Instruction::LShr:
1607 case Instruction::UDiv:
1608 case Instruction::URem: // Cast to unsigned first
1609 shouldCast = true;
1610 castIsSigned = false;
1611 break;
Chris Lattner7ce1ee42007-09-22 20:16:48 +00001612 case Instruction::GetElementPtr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001613 case Instruction::AShr:
1614 case Instruction::SDiv:
1615 case Instruction::SRem: // Cast to signed first
1616 shouldCast = true;
1617 castIsSigned = true;
1618 break;
1619 }
1620
1621 // Write out the casted operand if we should, otherwise just write the
1622 // operand.
1623 if (shouldCast) {
1624 Out << "((";
1625 printSimpleType(Out, OpTy, castIsSigned);
1626 Out << ")";
1627 writeOperand(Operand);
1628 Out << ")";
1629 } else
1630 writeOperand(Operand);
1631}
1632
1633// Write the operand with a cast to another type based on the icmp predicate
1634// being used.
Chris Lattner389c9142007-09-15 06:51:03 +00001635void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1636 // This has to do a cast to ensure the operand has the right signedness.
1637 // Also, if the operand is a pointer, we make sure to cast to an integer when
1638 // doing the comparison both for signedness and so that the C compiler doesn't
1639 // optimize things like "p < NULL" to false (p may contain an integer value
1640 // f.e.).
1641 bool shouldCast = Cmp.isRelational();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642
1643 // Write out the casted operand if we should, otherwise just write the
1644 // operand.
Chris Lattner389c9142007-09-15 06:51:03 +00001645 if (!shouldCast) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001646 writeOperand(Operand);
Chris Lattner389c9142007-09-15 06:51:03 +00001647 return;
1648 }
1649
1650 // Should this be a signed comparison? If so, convert to signed.
Nick Lewyckyb0796c62009-10-25 05:20:17 +00001651 bool castIsSigned = Cmp.isSigned();
Chris Lattner389c9142007-09-15 06:51:03 +00001652
1653 // If the operand was a pointer, convert to a large integer type.
1654 const Type* OpTy = Operand->getType();
1655 if (isa<PointerType>(OpTy))
Owen Anderson35b47072009-08-13 21:58:54 +00001656 OpTy = TD->getIntPtrType(Operand->getContext());
Chris Lattner389c9142007-09-15 06:51:03 +00001657
1658 Out << "((";
1659 printSimpleType(Out, OpTy, castIsSigned);
1660 Out << ")";
1661 writeOperand(Operand);
1662 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001663}
1664
1665// generateCompilerSpecificCode - This is where we add conditional compilation
1666// directives to cater to specific compilers as need be.
1667//
David Greene302008d2009-07-14 20:18:05 +00001668static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
Dan Gohman3f795232008-04-02 23:52:49 +00001669 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001670 // Alloca is hard to get, and we don't want to include stdlib.h here.
1671 Out << "/* get a declaration for alloca */\n"
1672 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1673 << "#define alloca(x) __builtin_alloca((x))\n"
Anton Korobeynikov9664a752009-08-05 09:31:07 +00001674 << "#define _alloca(x) __builtin_alloca((x))\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001675 << "#elif defined(__APPLE__)\n"
1676 << "extern void *__builtin_alloca(unsigned long);\n"
1677 << "#define alloca(x) __builtin_alloca(x)\n"
1678 << "#define longjmp _longjmp\n"
1679 << "#define setjmp _setjmp\n"
1680 << "#elif defined(__sun__)\n"
1681 << "#if defined(__sparcv9)\n"
1682 << "extern void *__builtin_alloca(unsigned long);\n"
1683 << "#else\n"
1684 << "extern void *__builtin_alloca(unsigned int);\n"
1685 << "#endif\n"
1686 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikov9664a752009-08-05 09:31:07 +00001687 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001688 << "#define alloca(x) __builtin_alloca(x)\n"
1689 << "#elif defined(_MSC_VER)\n"
1690 << "#define inline _inline\n"
1691 << "#define alloca(x) _alloca(x)\n"
1692 << "#else\n"
1693 << "#include <alloca.h>\n"
1694 << "#endif\n\n";
1695
1696 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1697 // If we aren't being compiled with GCC, just drop these attributes.
1698 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1699 << "#define __attribute__(X)\n"
1700 << "#endif\n\n";
1701
1702 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1703 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1704 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1705 << "#elif defined(__GNUC__)\n"
1706 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1707 << "#else\n"
1708 << "#define __EXTERNAL_WEAK__\n"
1709 << "#endif\n\n";
1710
1711 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1712 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1713 << "#define __ATTRIBUTE_WEAK__\n"
1714 << "#elif defined(__GNUC__)\n"
1715 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1716 << "#else\n"
1717 << "#define __ATTRIBUTE_WEAK__\n"
1718 << "#endif\n\n";
1719
1720 // Add hidden visibility support. FIXME: APPLE_CC?
1721 Out << "#if defined(__GNUC__)\n"
1722 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1723 << "#endif\n\n";
1724
1725 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1726 // From the GCC documentation:
1727 //
1728 // double __builtin_nan (const char *str)
1729 //
1730 // This is an implementation of the ISO C99 function nan.
1731 //
1732 // Since ISO C99 defines this function in terms of strtod, which we do
1733 // not implement, a description of the parsing is in order. The string is
1734 // parsed as by strtol; that is, the base is recognized by leading 0 or
1735 // 0x prefixes. The number parsed is placed in the significand such that
1736 // the least significant bit of the number is at the least significant
1737 // bit of the significand. The number is truncated to fit the significand
1738 // field provided. The significand is forced to be a quiet NaN.
1739 //
1740 // This function, if given a string literal, is evaluated early enough
1741 // that it is considered a compile-time constant.
1742 //
1743 // float __builtin_nanf (const char *str)
1744 //
1745 // Similar to __builtin_nan, except the return type is float.
1746 //
1747 // double __builtin_inf (void)
1748 //
1749 // Similar to __builtin_huge_val, except a warning is generated if the
1750 // target floating-point format does not support infinities. This
1751 // function is suitable for implementing the ISO C99 macro INFINITY.
1752 //
1753 // float __builtin_inff (void)
1754 //
1755 // Similar to __builtin_inf, except the return type is float.
1756 Out << "#ifdef __GNUC__\n"
1757 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1758 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1759 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1760 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1761 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1762 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1763 << "#define LLVM_PREFETCH(addr,rw,locality) "
1764 "__builtin_prefetch(addr,rw,locality)\n"
1765 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1766 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1767 << "#define LLVM_ASM __asm__\n"
1768 << "#else\n"
1769 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1770 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1771 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1772 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1773 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1774 << "#define LLVM_INFF 0.0F /* Float */\n"
1775 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1776 << "#define __ATTRIBUTE_CTOR__\n"
1777 << "#define __ATTRIBUTE_DTOR__\n"
1778 << "#define LLVM_ASM(X)\n"
1779 << "#endif\n\n";
1780
1781 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1782 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1783 << "#define __builtin_stack_restore(X) /* noop */\n"
1784 << "#endif\n\n";
1785
Dan Gohman3f795232008-04-02 23:52:49 +00001786 // Output typedefs for 128-bit integers. If these are needed with a
1787 // 32-bit target or with a C compiler that doesn't support mode(TI),
1788 // more drastic measures will be needed.
Chris Lattnerab6d3382008-06-16 04:25:29 +00001789 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1790 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1791 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1792 << "#endif\n\n";
Dan Gohmana2245af2008-04-02 19:40:14 +00001793
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001794 // Output target-specific code that should be inserted into main.
1795 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001796}
1797
1798/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1799/// the StaticTors set.
1800static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1801 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1802 if (!InitList) return;
1803
1804 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1805 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1806 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1807
1808 if (CS->getOperand(1)->isNullValue())
1809 return; // Found a null terminator, exit printing.
1810 Constant *FP = CS->getOperand(1);
1811 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1812 if (CE->isCast())
1813 FP = CE->getOperand(0);
1814 if (Function *F = dyn_cast<Function>(FP))
1815 StaticTors.insert(F);
1816 }
1817}
1818
1819enum SpecialGlobalClass {
1820 NotSpecial = 0,
1821 GlobalCtors, GlobalDtors,
1822 NotPrinted
1823};
1824
1825/// getGlobalVariableClass - If this is a global that is specially recognized
1826/// by LLVM, return a code that indicates how we should handle it.
1827static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1828 // If this is a global ctors/dtors list, handle it now.
1829 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1830 if (GV->getName() == "llvm.global_ctors")
1831 return GlobalCtors;
1832 else if (GV->getName() == "llvm.global_dtors")
1833 return GlobalDtors;
1834 }
1835
1836 // Otherwise, it it is other metadata, don't print it. This catches things
1837 // like debug information.
1838 if (GV->getSection() == "llvm.metadata")
1839 return NotPrinted;
1840
1841 return NotSpecial;
1842}
1843
Anton Korobeynikov865e6752009-08-05 09:29:56 +00001844// PrintEscapedString - Print each character of the specified string, escaping
1845// it if it is not printable or if it is an escape char.
1846static void PrintEscapedString(const char *Str, unsigned Length,
1847 raw_ostream &Out) {
1848 for (unsigned i = 0; i != Length; ++i) {
1849 unsigned char C = Str[i];
1850 if (isprint(C) && C != '\\' && C != '"')
1851 Out << C;
1852 else if (C == '\\')
1853 Out << "\\\\";
1854 else if (C == '\"')
1855 Out << "\\\"";
1856 else if (C == '\t')
1857 Out << "\\t";
1858 else
1859 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1860 }
1861}
1862
1863// PrintEscapedString - Print each character of the specified string, escaping
1864// it if it is not printable or if it is an escape char.
1865static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1866 PrintEscapedString(Str.c_str(), Str.size(), Out);
1867}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001868
1869bool CWriter::doInitialization(Module &M) {
Daniel Dunbar5392e062009-07-17 03:43:21 +00001870 FunctionPass::doInitialization(M);
1871
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001872 // Initialize
1873 TheModule = &M;
1874
1875 TD = new TargetData(&M);
1876 IL = new IntrinsicLowering(*TD);
1877 IL->AddPrototypes(M);
1878
Chris Lattner63ab9bb2010-01-17 18:22:35 +00001879#if 0
1880 std::string Triple = TheModule->getTargetTriple();
1881 if (Triple.empty())
1882 Triple = llvm::sys::getHostTriple();
1883
1884 std::string E;
1885 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
1886 TAsm = Match->createAsmInfo(Triple);
1887#endif
1888 TAsm = new CBEMCAsmInfo();
1889 Mang = new Mangler(*TAsm);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001890
1891 // Keep track of which functions are static ctors/dtors so they can have
1892 // an attribute added to their prototypes.
1893 std::set<Function*> StaticCtors, StaticDtors;
1894 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1895 I != E; ++I) {
1896 switch (getGlobalVariableClass(I)) {
1897 default: break;
1898 case GlobalCtors:
1899 FindStaticTors(I, StaticCtors);
1900 break;
1901 case GlobalDtors:
1902 FindStaticTors(I, StaticDtors);
1903 break;
1904 }
1905 }
1906
1907 // get declaration for alloca
1908 Out << "/* Provide Declarations */\n";
1909 Out << "#include <stdarg.h>\n"; // Varargs support
1910 Out << "#include <setjmp.h>\n"; // Unwind support
Dan Gohman3f795232008-04-02 23:52:49 +00001911 generateCompilerSpecificCode(Out, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001912
1913 // Provide a definition for `bool' if not compiling with a C++ compiler.
1914 Out << "\n"
1915 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1916
1917 << "\n\n/* Support for floating point constants */\n"
1918 << "typedef unsigned long long ConstantDoubleTy;\n"
1919 << "typedef unsigned int ConstantFloatTy;\n"
Dale Johannesen137cef62007-09-17 00:38:27 +00001920 << "typedef struct { unsigned long long f1; unsigned short f2; "
1921 "unsigned short pad[3]; } ConstantFP80Ty;\n"
Dale Johannesen091dcfd2007-10-15 01:05:37 +00001922 // This is used for both kinds of 128-bit long double; meaning differs.
Dale Johannesen137cef62007-09-17 00:38:27 +00001923 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1924 " ConstantFP128Ty;\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001925 << "\n\n/* Global Declarations */\n";
1926
1927 // First output all the declarations for the program, because C requires
1928 // Functions & globals to be declared before they are used.
1929 //
Anton Korobeynikov865e6752009-08-05 09:29:56 +00001930 if (!M.getModuleInlineAsm().empty()) {
1931 Out << "/* Module asm statements */\n"
1932 << "asm(";
1933
1934 // Split the string into lines, to make it easier to read the .ll file.
1935 std::string Asm = M.getModuleInlineAsm();
1936 size_t CurPos = 0;
1937 size_t NewLine = Asm.find_first_of('\n', CurPos);
1938 while (NewLine != std::string::npos) {
1939 // We found a newline, print the portion of the asm string from the
1940 // last newline up to this newline.
1941 Out << "\"";
1942 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1943 Out);
1944 Out << "\\n\"\n";
1945 CurPos = NewLine+1;
1946 NewLine = Asm.find_first_of('\n', CurPos);
1947 }
1948 Out << "\"";
1949 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1950 Out << "\");\n"
1951 << "/* End Module asm statements */\n";
1952 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001953
1954 // Loop over the symbol table, emitting all named constants...
1955 printModuleTypes(M.getTypeSymbolTable());
1956
1957 // Global variable declarations...
1958 if (!M.global_empty()) {
1959 Out << "\n/* External Global Variable Declarations */\n";
1960 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1961 I != E; ++I) {
1962
Dale Johannesen49c44122008-05-14 20:12:51 +00001963 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1964 I->hasCommonLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001965 Out << "extern ";
1966 else if (I->hasDLLImportLinkage())
1967 Out << "__declspec(dllimport) ";
1968 else
1969 continue; // Internal Global
1970
1971 // Thread Local Storage
1972 if (I->isThreadLocal())
1973 Out << "__thread ";
1974
1975 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1976
1977 if (I->hasExternalWeakLinkage())
1978 Out << " __EXTERNAL_WEAK__";
1979 Out << ";\n";
1980 }
1981 }
1982
1983 // Function declarations
1984 Out << "\n/* Function Declarations */\n";
1985 Out << "double fmod(double, double);\n"; // Support for FP rem
1986 Out << "float fmodf(float, float);\n";
Dale Johannesen137cef62007-09-17 00:38:27 +00001987 Out << "long double fmodl(long double, long double);\n";
Evan Chengd2d22fe2008-06-07 07:50:29 +00001988
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001989 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1990 // Don't print declarations for intrinsic functions.
Duncan Sands79d28872007-12-03 20:06:50 +00001991 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001992 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1993 if (I->hasExternalWeakLinkage())
1994 Out << "extern ";
1995 printFunctionSignature(I, true);
Evan Chengd2d22fe2008-06-07 07:50:29 +00001996 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001997 Out << " __ATTRIBUTE_WEAK__";
1998 if (I->hasExternalWeakLinkage())
1999 Out << " __EXTERNAL_WEAK__";
2000 if (StaticCtors.count(I))
2001 Out << " __ATTRIBUTE_CTOR__";
2002 if (StaticDtors.count(I))
2003 Out << " __ATTRIBUTE_DTOR__";
2004 if (I->hasHiddenVisibility())
2005 Out << " __HIDDEN__";
Evan Chengd2d22fe2008-06-07 07:50:29 +00002006
2007 if (I->hasName() && I->getName()[0] == 1)
Daniel Dunbar936763a2009-07-22 21:10:12 +00002008 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
Evan Chengd2d22fe2008-06-07 07:50:29 +00002009
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002010 Out << ";\n";
2011 }
2012 }
2013
2014 // Output the global variable declarations
2015 if (!M.global_empty()) {
2016 Out << "\n\n/* Global Variable Declarations */\n";
2017 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2018 I != E; ++I)
2019 if (!I->isDeclaration()) {
2020 // Ignore special globals, such as debug info.
2021 if (getGlobalVariableClass(I))
2022 continue;
2023
Rafael Espindolaa168fc92009-01-15 20:18:42 +00002024 if (I->hasLocalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002025 Out << "static ";
2026 else
2027 Out << "extern ";
2028
2029 // Thread Local Storage
2030 if (I->isThreadLocal())
2031 Out << "__thread ";
2032
2033 printType(Out, I->getType()->getElementType(), false,
2034 GetValueName(I));
2035
2036 if (I->hasLinkOnceLinkage())
2037 Out << " __attribute__((common))";
Dale Johannesen49c44122008-05-14 20:12:51 +00002038 else if (I->hasCommonLinkage()) // FIXME is this right?
2039 Out << " __ATTRIBUTE_WEAK__";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002040 else if (I->hasWeakLinkage())
2041 Out << " __ATTRIBUTE_WEAK__";
2042 else if (I->hasExternalWeakLinkage())
2043 Out << " __EXTERNAL_WEAK__";
2044 if (I->hasHiddenVisibility())
2045 Out << " __HIDDEN__";
2046 Out << ";\n";
2047 }
2048 }
2049
2050 // Output the global variable definitions and contents...
2051 if (!M.global_empty()) {
2052 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Evan Chengd2d22fe2008-06-07 07:50:29 +00002053 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002054 I != E; ++I)
2055 if (!I->isDeclaration()) {
2056 // Ignore special globals, such as debug info.
2057 if (getGlobalVariableClass(I))
2058 continue;
2059
Rafael Espindolaa168fc92009-01-15 20:18:42 +00002060 if (I->hasLocalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002061 Out << "static ";
2062 else if (I->hasDLLImportLinkage())
2063 Out << "__declspec(dllimport) ";
2064 else if (I->hasDLLExportLinkage())
2065 Out << "__declspec(dllexport) ";
2066
2067 // Thread Local Storage
2068 if (I->isThreadLocal())
2069 Out << "__thread ";
2070
2071 printType(Out, I->getType()->getElementType(), false,
2072 GetValueName(I));
2073 if (I->hasLinkOnceLinkage())
2074 Out << " __attribute__((common))";
2075 else if (I->hasWeakLinkage())
2076 Out << " __ATTRIBUTE_WEAK__";
Dale Johannesen49c44122008-05-14 20:12:51 +00002077 else if (I->hasCommonLinkage())
2078 Out << " __ATTRIBUTE_WEAK__";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002079
2080 if (I->hasHiddenVisibility())
2081 Out << " __HIDDEN__";
2082
2083 // If the initializer is not null, emit the initializer. If it is null,
2084 // we try to avoid emitting large amounts of zeros. The problem with
2085 // this, however, occurs when the variable has weak linkage. In this
2086 // case, the assembler will complain about the variable being both weak
2087 // and common, so we disable this optimization.
Dale Johannesen49c44122008-05-14 20:12:51 +00002088 // FIXME common linkage should avoid this problem.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002089 if (!I->getInitializer()->isNullValue()) {
2090 Out << " = " ;
Dan Gohmanad831302008-07-24 17:57:48 +00002091 writeOperand(I->getInitializer(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002092 } else if (I->hasWeakLinkage()) {
2093 // We have to specify an initializer, but it doesn't have to be
2094 // complete. If the value is an aggregate, print out { 0 }, and let
2095 // the compiler figure out the rest of the zeros.
2096 Out << " = " ;
2097 if (isa<StructType>(I->getInitializer()->getType()) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002098 isa<VectorType>(I->getInitializer()->getType())) {
2099 Out << "{ 0 }";
Dan Gohman5d995b02008-06-02 21:30:49 +00002100 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
2101 // As with structs and vectors, but with an extra set of braces
2102 // because arrays are wrapped in structs.
2103 Out << "{ { 0 } }";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002104 } else {
2105 // Just print it out normally.
Dan Gohmanad831302008-07-24 17:57:48 +00002106 writeOperand(I->getInitializer(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002107 }
2108 }
2109 Out << ";\n";
2110 }
2111 }
2112
2113 if (!M.empty())
2114 Out << "\n\n/* Function Bodies */\n";
2115
2116 // Emit some helper functions for dealing with FCMP instruction's
2117 // predicates
2118 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2119 Out << "return X == X && Y == Y; }\n";
2120 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2121 Out << "return X != X || Y != Y; }\n";
2122 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
2123 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
2124 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
2125 Out << "return X != Y; }\n";
2126 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
2127 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
2128 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
2129 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
2130 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
2131 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
2132 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
2133 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
2134 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
2135 Out << "return X == Y ; }\n";
2136 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
2137 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
2138 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
2139 Out << "return X < Y ; }\n";
2140 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
2141 Out << "return X > Y ; }\n";
2142 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
2143 Out << "return X <= Y ; }\n";
2144 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
2145 Out << "return X >= Y ; }\n";
2146 return false;
2147}
2148
2149
2150/// Output all floating point constants that cannot be printed accurately...
2151void CWriter::printFloatingPointConstants(Function &F) {
2152 // Scan the module for floating point constants. If any FP constant is used
2153 // in the function, we want to redirect it here so that we do not depend on
2154 // the precision of the printed form, unless the printed form preserves
2155 // precision.
2156 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002157 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2158 I != E; ++I)
Chris Lattnerf6e12012008-10-22 04:53:16 +00002159 printFloatingPointConstants(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002160
2161 Out << '\n';
2162}
2163
Chris Lattnerf6e12012008-10-22 04:53:16 +00002164void CWriter::printFloatingPointConstants(const Constant *C) {
2165 // If this is a constant expression, recursively check for constant fp values.
2166 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2167 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2168 printFloatingPointConstants(CE->getOperand(i));
2169 return;
2170 }
2171
2172 // Otherwise, check for a FP constant that we need to print.
2173 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2174 if (FPC == 0 ||
2175 // Do not put in FPConstantMap if safe.
2176 isFPCSafeToPrint(FPC) ||
2177 // Already printed this constant?
2178 FPConstantMap.count(FPC))
2179 return;
2180
2181 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2182
Owen Anderson35b47072009-08-13 21:58:54 +00002183 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
Chris Lattnerf6e12012008-10-22 04:53:16 +00002184 double Val = FPC->getValueAPF().convertToDouble();
2185 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2186 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2187 << " = 0x" << utohexstr(i)
2188 << "ULL; /* " << Val << " */\n";
Owen Anderson35b47072009-08-13 21:58:54 +00002189 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
Chris Lattnerf6e12012008-10-22 04:53:16 +00002190 float Val = FPC->getValueAPF().convertToFloat();
2191 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2192 getZExtValue();
2193 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2194 << " = 0x" << utohexstr(i)
2195 << "U; /* " << Val << " */\n";
Owen Anderson35b47072009-08-13 21:58:54 +00002196 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
Chris Lattnerf6e12012008-10-22 04:53:16 +00002197 // api needed to prevent premature destruction
2198 APInt api = FPC->getValueAPF().bitcastToAPInt();
2199 const uint64_t *p = api.getRawData();
2200 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
Dale Johannesen0a92eac2009-03-23 21:16:53 +00002201 << " = { 0x" << utohexstr(p[0])
2202 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
Chris Lattnerf6e12012008-10-22 04:53:16 +00002203 << "}; /* Long double constant */\n";
Anton Korobeynikov3e721692009-08-26 17:39:23 +00002204 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2205 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
Chris Lattnerf6e12012008-10-22 04:53:16 +00002206 APInt api = FPC->getValueAPF().bitcastToAPInt();
2207 const uint64_t *p = api.getRawData();
2208 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2209 << " = { 0x"
2210 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2211 << "}; /* Long double constant */\n";
2212
2213 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00002214 llvm_unreachable("Unknown float type!");
Chris Lattnerf6e12012008-10-22 04:53:16 +00002215 }
2216}
2217
2218
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002219
2220/// printSymbolTable - Run through symbol table looking for type names. If a
2221/// type name is found, emit its declaration...
2222///
2223void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
2224 Out << "/* Helper union for bitcasts */\n";
2225 Out << "typedef union {\n";
2226 Out << " unsigned int Int32;\n";
2227 Out << " unsigned long long Int64;\n";
2228 Out << " float Float;\n";
2229 Out << " double Double;\n";
2230 Out << "} llvmBitCastUnion;\n";
2231
2232 // We are only interested in the type plane of the symbol table.
2233 TypeSymbolTable::const_iterator I = TST.begin();
2234 TypeSymbolTable::const_iterator End = TST.end();
2235
2236 // If there are no type names, exit early.
2237 if (I == End) return;
2238
2239 // Print out forward declarations for structure types before anything else!
2240 Out << "/* Structure forward decls */\n";
2241 for (; I != End; ++I) {
Chris Lattnerd2f59b82010-01-13 19:54:07 +00002242 std::string Name = "struct " + Mangle("l_"+I->first);
2243 Out << Name << ";\n";
2244 TypeNames.insert(std::make_pair(I->second, Name));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002245 }
2246
2247 Out << '\n';
2248
2249 // Now we can print out typedefs. Above, we guaranteed that this can only be
2250 // for struct or opaque types.
2251 Out << "/* Typedefs */\n";
2252 for (I = TST.begin(); I != End; ++I) {
Chris Lattnerd2f59b82010-01-13 19:54:07 +00002253 std::string Name = Mangle("l_"+I->first);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002254 Out << "typedef ";
Chris Lattnerd2f59b82010-01-13 19:54:07 +00002255 printType(Out, I->second, false, Name);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002256 Out << ";\n";
2257 }
2258
2259 Out << '\n';
2260
2261 // Keep track of which structures have been printed so far...
Dan Gohman5d995b02008-06-02 21:30:49 +00002262 std::set<const Type *> StructPrinted;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263
2264 // Loop over all structures then push them into the stack so they are
2265 // printed in the correct order.
2266 //
2267 Out << "/* Structure contents */\n";
2268 for (I = TST.begin(); I != End; ++I)
Dan Gohman5d995b02008-06-02 21:30:49 +00002269 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002270 // Only print out used types!
Dan Gohman5d995b02008-06-02 21:30:49 +00002271 printContainedStructs(I->second, StructPrinted);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002272}
2273
2274// Push the struct onto the stack and recursively push all structs
2275// this one depends on.
2276//
2277// TODO: Make this work properly with vector types
2278//
2279void CWriter::printContainedStructs(const Type *Ty,
Dan Gohman5d995b02008-06-02 21:30:49 +00002280 std::set<const Type*> &StructPrinted) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002281 // Don't walk through pointers.
2282 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
2283
2284 // Print all contained types first.
2285 for (Type::subtype_iterator I = Ty->subtype_begin(),
2286 E = Ty->subtype_end(); I != E; ++I)
2287 printContainedStructs(*I, StructPrinted);
2288
Dan Gohman5d995b02008-06-02 21:30:49 +00002289 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002290 // Check to see if we have already printed this struct.
Dan Gohman5d995b02008-06-02 21:30:49 +00002291 if (StructPrinted.insert(Ty).second) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002292 // Print structure type out.
Dan Gohman5d995b02008-06-02 21:30:49 +00002293 std::string Name = TypeNames[Ty];
2294 printType(Out, Ty, false, Name, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002295 Out << ";\n\n";
2296 }
2297 }
2298}
2299
2300void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
2301 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel949a4b72008-03-03 21:46:28 +00002302 bool isStructReturn = F->hasStructRetAttr();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002303
Rafael Espindolaa168fc92009-01-15 20:18:42 +00002304 if (F->hasLocalLinkage()) Out << "static ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002305 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2306 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
2307 switch (F->getCallingConv()) {
2308 case CallingConv::X86_StdCall:
Nick Lewyckyc0b01ea2008-11-26 03:17:27 +00002309 Out << "__attribute__((stdcall)) ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002310 break;
2311 case CallingConv::X86_FastCall:
Nick Lewyckyc0b01ea2008-11-26 03:17:27 +00002312 Out << "__attribute__((fastcall)) ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002313 break;
Sandeep Patel5838baa2009-09-02 08:44:58 +00002314 default:
2315 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002316 }
2317
2318 // Loop over the arguments, printing them...
2319 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Devang Pateld222f862008-09-25 21:00:45 +00002320 const AttrListPtr &PAL = F->getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002321
2322 std::stringstream FunctionInnards;
2323
2324 // Print out the name...
2325 FunctionInnards << GetValueName(F) << '(';
2326
2327 bool PrintedArg = false;
2328 if (!F->isDeclaration()) {
2329 if (!F->arg_empty()) {
2330 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
Evan Cheng2054cb02008-01-11 03:07:46 +00002331 unsigned Idx = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002332
2333 // If this is a struct-return function, don't print the hidden
2334 // struct-return argument.
2335 if (isStructReturn) {
2336 assert(I != E && "Invalid struct return function!");
2337 ++I;
Evan Cheng2054cb02008-01-11 03:07:46 +00002338 ++Idx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002339 }
2340
2341 std::string ArgName;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002342 for (; I != E; ++I) {
2343 if (PrintedArg) FunctionInnards << ", ";
2344 if (I->hasName() || !Prototype)
2345 ArgName = GetValueName(I);
2346 else
2347 ArgName = "";
Evan Cheng2054cb02008-01-11 03:07:46 +00002348 const Type *ArgTy = I->getType();
Devang Pateld222f862008-09-25 21:00:45 +00002349 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng17254e62008-01-11 09:12:49 +00002350 ArgTy = cast<PointerType>(ArgTy)->getElementType();
Chris Lattner8bbc8592008-03-02 08:07:24 +00002351 ByValParams.insert(I);
Evan Cheng17254e62008-01-11 09:12:49 +00002352 }
Evan Cheng2054cb02008-01-11 03:07:46 +00002353 printType(FunctionInnards, ArgTy,
Devang Pateld222f862008-09-25 21:00:45 +00002354 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002355 ArgName);
2356 PrintedArg = true;
2357 ++Idx;
2358 }
2359 }
2360 } else {
2361 // Loop over the arguments, printing them.
2362 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
Evan Chengf8956382008-01-11 23:10:11 +00002363 unsigned Idx = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002364
2365 // If this is a struct-return function, don't print the hidden
2366 // struct-return argument.
2367 if (isStructReturn) {
2368 assert(I != E && "Invalid struct return function!");
2369 ++I;
Evan Chengf8956382008-01-11 23:10:11 +00002370 ++Idx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002371 }
2372
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002373 for (; I != E; ++I) {
2374 if (PrintedArg) FunctionInnards << ", ";
Evan Chengf8956382008-01-11 23:10:11 +00002375 const Type *ArgTy = *I;
Devang Pateld222f862008-09-25 21:00:45 +00002376 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Chengf8956382008-01-11 23:10:11 +00002377 assert(isa<PointerType>(ArgTy));
2378 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2379 }
2380 printType(FunctionInnards, ArgTy,
Devang Pateld222f862008-09-25 21:00:45 +00002381 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002382 PrintedArg = true;
2383 ++Idx;
2384 }
2385 }
2386
2387 // Finish printing arguments... if this is a vararg function, print the ...,
2388 // unless there are no known types, in which case, we just emit ().
2389 //
2390 if (FT->isVarArg() && PrintedArg) {
2391 if (PrintedArg) FunctionInnards << ", ";
2392 FunctionInnards << "..."; // Output varargs portion of signature!
2393 } else if (!FT->isVarArg() && !PrintedArg) {
2394 FunctionInnards << "void"; // ret() -> ret(void) in C.
2395 }
2396 FunctionInnards << ')';
2397
2398 // Get the return tpe for the function.
2399 const Type *RetTy;
2400 if (!isStructReturn)
2401 RetTy = F->getReturnType();
2402 else {
2403 // If this is a struct-return function, print the struct-return type.
2404 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2405 }
2406
2407 // Print out the return type and the signature built above.
2408 printType(Out, RetTy,
Devang Pateld222f862008-09-25 21:00:45 +00002409 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002410 FunctionInnards.str());
2411}
2412
2413static inline bool isFPIntBitCast(const Instruction &I) {
2414 if (!isa<BitCastInst>(I))
2415 return false;
2416 const Type *SrcTy = I.getOperand(0)->getType();
2417 const Type *DstTy = I.getType();
2418 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2419 (DstTy->isFloatingPoint() && SrcTy->isInteger());
2420}
2421
2422void CWriter::printFunction(Function &F) {
2423 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel949a4b72008-03-03 21:46:28 +00002424 bool isStructReturn = F.hasStructRetAttr();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002425
2426 printFunctionSignature(&F, false);
2427 Out << " {\n";
2428
2429 // If this is a struct return function, handle the result with magic.
2430 if (isStructReturn) {
2431 const Type *StructTy =
2432 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2433 Out << " ";
2434 printType(Out, StructTy, false, "StructReturn");
2435 Out << "; /* Struct return temporary */\n";
2436
2437 Out << " ";
2438 printType(Out, F.arg_begin()->getType(), false,
2439 GetValueName(F.arg_begin()));
2440 Out << " = &StructReturn;\n";
2441 }
2442
2443 bool PrintedVar = false;
2444
2445 // print local variable information for the function
2446 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2447 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2448 Out << " ";
2449 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2450 Out << "; /* Address-exposed local */\n";
2451 PrintedVar = true;
Owen Anderson35b47072009-08-13 21:58:54 +00002452 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2453 !isInlinableInst(*I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002454 Out << " ";
2455 printType(Out, I->getType(), false, GetValueName(&*I));
2456 Out << ";\n";
2457
2458 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2459 Out << " ";
2460 printType(Out, I->getType(), false,
2461 GetValueName(&*I)+"__PHI_TEMPORARY");
2462 Out << ";\n";
2463 }
2464 PrintedVar = true;
2465 }
2466 // We need a temporary for the BitCast to use so it can pluck a value out
2467 // of a union to do the BitCast. This is separate from the need for a
2468 // variable to hold the result of the BitCast.
2469 if (isFPIntBitCast(*I)) {
2470 Out << " llvmBitCastUnion " << GetValueName(&*I)
2471 << "__BITCAST_TEMPORARY;\n";
2472 PrintedVar = true;
2473 }
2474 }
2475
2476 if (PrintedVar)
2477 Out << '\n';
2478
2479 if (F.hasExternalLinkage() && F.getName() == "main")
2480 Out << " CODE_FOR_MAIN();\n";
2481
2482 // print the basic blocks
2483 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2484 if (Loop *L = LI->getLoopFor(BB)) {
2485 if (L->getHeader() == BB && L->getParentLoop() == 0)
2486 printLoop(L);
2487 } else {
2488 printBasicBlock(BB);
2489 }
2490 }
2491
2492 Out << "}\n\n";
2493}
2494
2495void CWriter::printLoop(Loop *L) {
2496 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2497 << "' to make GCC happy */\n";
2498 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2499 BasicBlock *BB = L->getBlocks()[i];
2500 Loop *BBLoop = LI->getLoopFor(BB);
2501 if (BBLoop == L)
2502 printBasicBlock(BB);
2503 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2504 printLoop(BBLoop);
2505 }
2506 Out << " } while (1); /* end of syntactic loop '"
2507 << L->getHeader()->getName() << "' */\n";
2508}
2509
2510void CWriter::printBasicBlock(BasicBlock *BB) {
2511
2512 // Don't print the label for the basic block if there are no uses, or if
2513 // the only terminator use is the predecessor basic block's terminator.
2514 // We have to scan the use list because PHI nodes use basic blocks too but
2515 // do not require a label to be generated.
2516 //
2517 bool NeedsLabel = false;
2518 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2519 if (isGotoCodeNecessary(*PI, BB)) {
2520 NeedsLabel = true;
2521 break;
2522 }
2523
2524 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2525
2526 // Output all of the instructions in the basic block...
2527 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2528 ++II) {
2529 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
Owen Anderson35b47072009-08-13 21:58:54 +00002530 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2531 !isInlineAsm(*II))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002532 outputLValue(II);
2533 else
2534 Out << " ";
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002535 writeInstComputationInline(*II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002536 Out << ";\n";
2537 }
2538 }
2539
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002540 // Don't emit prefix or suffix for the terminator.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002541 visit(*BB->getTerminator());
2542}
2543
2544
2545// Specific Instruction type classes... note that all of the casts are
2546// necessary because we use the instruction classes as opaque types...
2547//
2548void CWriter::visitReturnInst(ReturnInst &I) {
2549 // If this is a struct return function, return the temporary struct.
Devang Patel949a4b72008-03-03 21:46:28 +00002550 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002551
2552 if (isStructReturn) {
2553 Out << " return StructReturn;\n";
2554 return;
2555 }
2556
2557 // Don't output a void return if this is the last basic block in the function
2558 if (I.getNumOperands() == 0 &&
2559 &*--I.getParent()->getParent()->end() == I.getParent() &&
2560 !I.getParent()->size() == 1) {
2561 return;
2562 }
2563
Dan Gohman93d04582008-04-23 21:49:29 +00002564 if (I.getNumOperands() > 1) {
2565 Out << " {\n";
2566 Out << " ";
2567 printType(Out, I.getParent()->getParent()->getReturnType());
2568 Out << " llvm_cbe_mrv_temp = {\n";
2569 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2570 Out << " ";
2571 writeOperand(I.getOperand(i));
2572 if (i != e - 1)
2573 Out << ",";
2574 Out << "\n";
2575 }
2576 Out << " };\n";
2577 Out << " return llvm_cbe_mrv_temp;\n";
2578 Out << " }\n";
2579 return;
2580 }
2581
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002582 Out << " return";
2583 if (I.getNumOperands()) {
2584 Out << ' ';
2585 writeOperand(I.getOperand(0));
2586 }
2587 Out << ";\n";
2588}
2589
2590void CWriter::visitSwitchInst(SwitchInst &SI) {
2591
2592 Out << " switch (";
2593 writeOperand(SI.getOperand(0));
2594 Out << ") {\n default:\n";
2595 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2596 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2597 Out << ";\n";
2598 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2599 Out << " case ";
2600 writeOperand(SI.getOperand(i));
2601 Out << ":\n";
2602 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2603 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2604 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattnerb44b4292009-12-03 00:50:42 +00002605 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002606 Out << " break;\n";
2607 }
2608 Out << " }\n";
2609}
2610
Chris Lattner4c3800f2009-10-28 00:19:10 +00002611void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
Chris Lattner20e88f52009-10-27 21:21:06 +00002612 Out << " goto *(void*)(";
2613 writeOperand(IBI.getOperand(0));
2614 Out << ");\n";
2615}
2616
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002617void CWriter::visitUnreachableInst(UnreachableInst &I) {
2618 Out << " /*UNREACHABLE*/;\n";
2619}
2620
2621bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2622 /// FIXME: This should be reenabled, but loop reordering safe!!
2623 return true;
2624
Chris Lattnerb44b4292009-12-03 00:50:42 +00002625 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002626 return true; // Not the direct successor, we need a goto.
2627
2628 //isa<SwitchInst>(From->getTerminator())
2629
2630 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2631 return true;
2632 return false;
2633}
2634
2635void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2636 BasicBlock *Successor,
2637 unsigned Indent) {
2638 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2639 PHINode *PN = cast<PHINode>(I);
2640 // Now we have to do the printing.
2641 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2642 if (!isa<UndefValue>(IV)) {
2643 Out << std::string(Indent, ' ');
2644 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2645 writeOperand(IV);
2646 Out << "; /* for PHI node */\n";
2647 }
2648 }
2649}
2650
2651void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2652 unsigned Indent) {
2653 if (isGotoCodeNecessary(CurBB, Succ)) {
2654 Out << std::string(Indent, ' ') << " goto ";
2655 writeOperand(Succ);
2656 Out << ";\n";
2657 }
2658}
2659
2660// Branch instruction printing - Avoid printing out a branch to a basic block
2661// that immediately succeeds the current one.
2662//
2663void CWriter::visitBranchInst(BranchInst &I) {
2664
2665 if (I.isConditional()) {
2666 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2667 Out << " if (";
2668 writeOperand(I.getCondition());
2669 Out << ") {\n";
2670
2671 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2672 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2673
2674 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2675 Out << " } else {\n";
2676 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2677 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2678 }
2679 } else {
2680 // First goto not necessary, assume second one is...
2681 Out << " if (!";
2682 writeOperand(I.getCondition());
2683 Out << ") {\n";
2684
2685 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2686 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2687 }
2688
2689 Out << " }\n";
2690 } else {
2691 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2692 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2693 }
2694 Out << "\n";
2695}
2696
2697// PHI nodes get copied into temporary values at the end of predecessor basic
2698// blocks. We now need to copy these temporary values into the REAL value for
2699// the PHI.
2700void CWriter::visitPHINode(PHINode &I) {
2701 writeOperand(&I);
2702 Out << "__PHI_TEMPORARY";
2703}
2704
2705
2706void CWriter::visitBinaryOperator(Instruction &I) {
2707 // binary instructions, shift instructions, setCond instructions.
2708 assert(!isa<PointerType>(I.getType()));
2709
2710 // We must cast the results of binary operations which might be promoted.
2711 bool needsCast = false;
Owen Anderson35b47072009-08-13 21:58:54 +00002712 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2713 (I.getType() == Type::getInt16Ty(I.getContext()))
2714 || (I.getType() == Type::getFloatTy(I.getContext()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002715 needsCast = true;
2716 Out << "((";
2717 printType(Out, I.getType(), false);
2718 Out << ")(";
2719 }
2720
2721 // If this is a negation operation, print it out as such. For FP, we don't
2722 // want to print "-0.0 - X".
Owen Anderson76f49252009-07-13 22:18:28 +00002723 if (BinaryOperator::isNeg(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002724 Out << "-(";
2725 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2726 Out << ")";
Owen Anderson76f49252009-07-13 22:18:28 +00002727 } else if (BinaryOperator::isFNeg(&I)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002728 Out << "-(";
2729 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2730 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002731 } else if (I.getOpcode() == Instruction::FRem) {
2732 // Output a call to fmod/fmodf instead of emitting a%b
Owen Anderson35b47072009-08-13 21:58:54 +00002733 if (I.getType() == Type::getFloatTy(I.getContext()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002734 Out << "fmodf(";
Owen Anderson35b47072009-08-13 21:58:54 +00002735 else if (I.getType() == Type::getDoubleTy(I.getContext()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002736 Out << "fmod(";
Dale Johannesen137cef62007-09-17 00:38:27 +00002737 else // all 3 flavors of long double
2738 Out << "fmodl(";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002739 writeOperand(I.getOperand(0));
2740 Out << ", ";
2741 writeOperand(I.getOperand(1));
2742 Out << ")";
2743 } else {
2744
2745 // Write out the cast of the instruction's value back to the proper type
2746 // if necessary.
2747 bool NeedsClosingParens = writeInstructionCast(I);
2748
2749 // Certain instructions require the operand to be forced to a specific type
2750 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2751 // below for operand 1
2752 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2753
2754 switch (I.getOpcode()) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002755 case Instruction::Add:
2756 case Instruction::FAdd: Out << " + "; break;
2757 case Instruction::Sub:
2758 case Instruction::FSub: Out << " - "; break;
2759 case Instruction::Mul:
2760 case Instruction::FMul: Out << " * "; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002761 case Instruction::URem:
2762 case Instruction::SRem:
2763 case Instruction::FRem: Out << " % "; break;
2764 case Instruction::UDiv:
2765 case Instruction::SDiv:
2766 case Instruction::FDiv: Out << " / "; break;
2767 case Instruction::And: Out << " & "; break;
2768 case Instruction::Or: Out << " | "; break;
2769 case Instruction::Xor: Out << " ^ "; break;
2770 case Instruction::Shl : Out << " << "; break;
2771 case Instruction::LShr:
2772 case Instruction::AShr: Out << " >> "; break;
Edwin Török4d9756a2009-07-08 20:53:28 +00002773 default:
2774#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +00002775 errs() << "Invalid operator type!" << I;
Edwin Török4d9756a2009-07-08 20:53:28 +00002776#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00002777 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002778 }
2779
2780 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2781 if (NeedsClosingParens)
2782 Out << "))";
2783 }
2784
2785 if (needsCast) {
2786 Out << "))";
2787 }
2788}
2789
2790void CWriter::visitICmpInst(ICmpInst &I) {
2791 // We must cast the results of icmp which might be promoted.
2792 bool needsCast = false;
2793
2794 // Write out the cast of the instruction's value back to the proper type
2795 // if necessary.
2796 bool NeedsClosingParens = writeInstructionCast(I);
2797
2798 // Certain icmp predicate require the operand to be forced to a specific type
2799 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2800 // below for operand 1
Chris Lattner389c9142007-09-15 06:51:03 +00002801 writeOperandWithCast(I.getOperand(0), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002802
2803 switch (I.getPredicate()) {
2804 case ICmpInst::ICMP_EQ: Out << " == "; break;
2805 case ICmpInst::ICMP_NE: Out << " != "; break;
2806 case ICmpInst::ICMP_ULE:
2807 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2808 case ICmpInst::ICMP_UGE:
2809 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2810 case ICmpInst::ICMP_ULT:
2811 case ICmpInst::ICMP_SLT: Out << " < "; break;
2812 case ICmpInst::ICMP_UGT:
2813 case ICmpInst::ICMP_SGT: Out << " > "; break;
Edwin Török4d9756a2009-07-08 20:53:28 +00002814 default:
2815#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +00002816 errs() << "Invalid icmp predicate!" << I;
Edwin Török4d9756a2009-07-08 20:53:28 +00002817#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00002818 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002819 }
2820
Chris Lattner389c9142007-09-15 06:51:03 +00002821 writeOperandWithCast(I.getOperand(1), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002822 if (NeedsClosingParens)
2823 Out << "))";
2824
2825 if (needsCast) {
2826 Out << "))";
2827 }
2828}
2829
2830void CWriter::visitFCmpInst(FCmpInst &I) {
2831 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2832 Out << "0";
2833 return;
2834 }
2835 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2836 Out << "1";
2837 return;
2838 }
2839
2840 const char* op = 0;
2841 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002842 default: llvm_unreachable("Illegal FCmp predicate");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002843 case FCmpInst::FCMP_ORD: op = "ord"; break;
2844 case FCmpInst::FCMP_UNO: op = "uno"; break;
2845 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2846 case FCmpInst::FCMP_UNE: op = "une"; break;
2847 case FCmpInst::FCMP_ULT: op = "ult"; break;
2848 case FCmpInst::FCMP_ULE: op = "ule"; break;
2849 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2850 case FCmpInst::FCMP_UGE: op = "uge"; break;
2851 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2852 case FCmpInst::FCMP_ONE: op = "one"; break;
2853 case FCmpInst::FCMP_OLT: op = "olt"; break;
2854 case FCmpInst::FCMP_OLE: op = "ole"; break;
2855 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2856 case FCmpInst::FCMP_OGE: op = "oge"; break;
2857 }
2858
2859 Out << "llvm_fcmp_" << op << "(";
2860 // Write the first operand
2861 writeOperand(I.getOperand(0));
2862 Out << ", ";
2863 // Write the second operand
2864 writeOperand(I.getOperand(1));
2865 Out << ")";
2866}
2867
2868static const char * getFloatBitCastField(const Type *Ty) {
2869 switch (Ty->getTypeID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002870 default: llvm_unreachable("Invalid Type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002871 case Type::FloatTyID: return "Float";
2872 case Type::DoubleTyID: return "Double";
2873 case Type::IntegerTyID: {
2874 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2875 if (NumBits <= 32)
2876 return "Int32";
2877 else
2878 return "Int64";
2879 }
2880 }
2881}
2882
2883void CWriter::visitCastInst(CastInst &I) {
2884 const Type *DstTy = I.getType();
2885 const Type *SrcTy = I.getOperand(0)->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886 if (isFPIntBitCast(I)) {
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002887 Out << '(';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002888 // These int<->float and long<->double casts need to be handled specially
2889 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2890 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2891 writeOperand(I.getOperand(0));
2892 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2893 << getFloatBitCastField(I.getType());
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002894 Out << ')';
2895 return;
2896 }
2897
2898 Out << '(';
2899 printCast(I.getOpcode(), SrcTy, DstTy);
2900
2901 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
Owen Anderson35b47072009-08-13 21:58:54 +00002902 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2903 I.getOpcode() == Instruction::SExt)
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002904 Out << "0-";
2905
2906 writeOperand(I.getOperand(0));
2907
Owen Anderson35b47072009-08-13 21:58:54 +00002908 if (DstTy == Type::getInt1Ty(I.getContext()) &&
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002909 (I.getOpcode() == Instruction::Trunc ||
2910 I.getOpcode() == Instruction::FPToUI ||
2911 I.getOpcode() == Instruction::FPToSI ||
2912 I.getOpcode() == Instruction::PtrToInt)) {
2913 // Make sure we really get a trunc to bool by anding the operand with 1
2914 Out << "&1u";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002915 }
2916 Out << ')';
2917}
2918
2919void CWriter::visitSelectInst(SelectInst &I) {
2920 Out << "((";
2921 writeOperand(I.getCondition());
2922 Out << ") ? (";
2923 writeOperand(I.getTrueValue());
2924 Out << ") : (";
2925 writeOperand(I.getFalseValue());
2926 Out << "))";
2927}
2928
2929
2930void CWriter::lowerIntrinsics(Function &F) {
2931 // This is used to keep track of intrinsics that get generated to a lowered
2932 // function. We must generate the prototypes before the function body which
2933 // will only be expanded on first use (by the loop below).
2934 std::vector<Function*> prototypesToGen;
2935
2936 // Examine all the instructions in this function to find the intrinsics that
2937 // need to be lowered.
2938 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2939 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2940 if (CallInst *CI = dyn_cast<CallInst>(I++))
2941 if (Function *F = CI->getCalledFunction())
2942 switch (F->getIntrinsicID()) {
2943 case Intrinsic::not_intrinsic:
Andrew Lenharth0531ec52008-02-16 14:46:26 +00002944 case Intrinsic::memory_barrier:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002945 case Intrinsic::vastart:
2946 case Intrinsic::vacopy:
2947 case Intrinsic::vaend:
2948 case Intrinsic::returnaddress:
2949 case Intrinsic::frameaddress:
2950 case Intrinsic::setjmp:
2951 case Intrinsic::longjmp:
2952 case Intrinsic::prefetch:
Dale Johannesenc339d8e2007-10-02 17:43:59 +00002953 case Intrinsic::powi:
Chris Lattner6a947cb2008-03-02 08:47:13 +00002954 case Intrinsic::x86_sse_cmp_ss:
2955 case Intrinsic::x86_sse_cmp_ps:
2956 case Intrinsic::x86_sse2_cmp_sd:
2957 case Intrinsic::x86_sse2_cmp_pd:
Chris Lattner709df322008-03-02 08:54:27 +00002958 case Intrinsic::ppc_altivec_lvsl:
Chris Lattner6a947cb2008-03-02 08:47:13 +00002959 // We directly implement these intrinsics
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002960 break;
2961 default:
2962 // If this is an intrinsic that directly corresponds to a GCC
2963 // builtin, we handle it.
2964 const char *BuiltinName = "";
2965#define GET_GCC_BUILTIN_NAME
2966#include "llvm/Intrinsics.gen"
2967#undef GET_GCC_BUILTIN_NAME
2968 // If we handle it, don't lower it.
2969 if (BuiltinName[0]) break;
2970
2971 // All other intrinsic calls we must lower.
2972 Instruction *Before = 0;
2973 if (CI != &BB->front())
2974 Before = prior(BasicBlock::iterator(CI));
2975
2976 IL->LowerIntrinsicCall(CI);
2977 if (Before) { // Move iterator to instruction after call
2978 I = Before; ++I;
2979 } else {
2980 I = BB->begin();
2981 }
2982 // If the intrinsic got lowered to another call, and that call has
2983 // a definition then we need to make sure its prototype is emitted
2984 // before any calls to it.
2985 if (CallInst *Call = dyn_cast<CallInst>(I))
2986 if (Function *NewF = Call->getCalledFunction())
2987 if (!NewF->isDeclaration())
2988 prototypesToGen.push_back(NewF);
2989
2990 break;
2991 }
2992
2993 // We may have collected some prototypes to emit in the loop above.
2994 // Emit them now, before the function that uses them is emitted. But,
2995 // be careful not to emit them twice.
2996 std::vector<Function*>::iterator I = prototypesToGen.begin();
2997 std::vector<Function*>::iterator E = prototypesToGen.end();
2998 for ( ; I != E; ++I) {
2999 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
3000 Out << '\n';
3001 printFunctionSignature(*I, true);
3002 Out << ";\n";
3003 }
3004 }
3005}
3006
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003007void CWriter::visitCallInst(CallInst &I) {
Chris Lattner8a3b6e42008-05-22 06:19:37 +00003008 if (isa<InlineAsm>(I.getOperand(0)))
3009 return visitInlineAsm(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003010
3011 bool WroteCallee = false;
3012
3013 // Handle intrinsic function calls first...
3014 if (Function *F = I.getCalledFunction())
Chris Lattnera74b9182008-03-02 08:29:41 +00003015 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3016 if (visitBuiltinCall(I, ID, WroteCallee))
Andrew Lenharth0531ec52008-02-16 14:46:26 +00003017 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003018
3019 Value *Callee = I.getCalledValue();
3020
3021 const PointerType *PTy = cast<PointerType>(Callee->getType());
3022 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3023
3024 // If this is a call to a struct-return function, assign to the first
3025 // parameter instead of passing it to the call.
Devang Pateld222f862008-09-25 21:00:45 +00003026 const AttrListPtr &PAL = I.getAttributes();
Evan Chengb8a072c2008-01-12 18:53:07 +00003027 bool hasByVal = I.hasByValArgument();
Devang Patel949a4b72008-03-03 21:46:28 +00003028 bool isStructRet = I.hasStructRetAttr();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003029 if (isStructRet) {
Chris Lattner8bbc8592008-03-02 08:07:24 +00003030 writeOperandDeref(I.getOperand(1));
Evan Chengf8956382008-01-11 23:10:11 +00003031 Out << " = ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003032 }
3033
3034 if (I.isTailCall()) Out << " /*tail*/ ";
3035
3036 if (!WroteCallee) {
3037 // If this is an indirect call to a struct return function, we need to cast
Evan Chengb8a072c2008-01-12 18:53:07 +00003038 // the pointer. Ditto for indirect calls with byval arguments.
3039 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003040
3041 // GCC is a real PITA. It does not permit codegening casts of functions to
3042 // function pointers if they are in a call (it generates a trap instruction
3043 // instead!). We work around this by inserting a cast to void* in between
3044 // the function and the function pointer cast. Unfortunately, we can't just
3045 // form the constant expression here, because the folder will immediately
3046 // nuke it.
3047 //
3048 // Note finally, that this is completely unsafe. ANSI C does not guarantee
3049 // that void* and function pointers have the same size. :( To deal with this
3050 // in the common case, we handle casts where the number of arguments passed
3051 // match exactly.
3052 //
3053 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
3054 if (CE->isCast())
3055 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
3056 NeedsCast = true;
3057 Callee = RF;
3058 }
3059
3060 if (NeedsCast) {
3061 // Ok, just cast the pointer type.
3062 Out << "((";
Evan Chengb8a072c2008-01-12 18:53:07 +00003063 if (isStructRet)
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003064 printStructReturnPointerFunctionType(Out, PAL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003065 cast<PointerType>(I.getCalledValue()->getType()));
Evan Chengb8a072c2008-01-12 18:53:07 +00003066 else if (hasByVal)
3067 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
3068 else
3069 printType(Out, I.getCalledValue()->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003070 Out << ")(void*)";
3071 }
3072 writeOperand(Callee);
3073 if (NeedsCast) Out << ')';
3074 }
3075
3076 Out << '(';
3077
3078 unsigned NumDeclaredParams = FTy->getNumParams();
3079
3080 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
3081 unsigned ArgNo = 0;
3082 if (isStructRet) { // Skip struct return argument.
3083 ++AI;
3084 ++ArgNo;
3085 }
3086
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003087 bool PrintedArg = false;
Evan Chengf8956382008-01-11 23:10:11 +00003088 for (; AI != AE; ++AI, ++ArgNo) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003089 if (PrintedArg) Out << ", ";
3090 if (ArgNo < NumDeclaredParams &&
3091 (*AI)->getType() != FTy->getParamType(ArgNo)) {
3092 Out << '(';
3093 printType(Out, FTy->getParamType(ArgNo),
Devang Pateld222f862008-09-25 21:00:45 +00003094 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003095 Out << ')';
3096 }
Evan Chengf8956382008-01-11 23:10:11 +00003097 // Check if the argument is expected to be passed by value.
Devang Pateld222f862008-09-25 21:00:45 +00003098 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
Chris Lattner8bbc8592008-03-02 08:07:24 +00003099 writeOperandDeref(*AI);
3100 else
3101 writeOperand(*AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003102 PrintedArg = true;
3103 }
3104 Out << ')';
3105}
3106
Chris Lattnera74b9182008-03-02 08:29:41 +00003107/// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3108/// if the entire call is handled, return false it it wasn't handled, and
3109/// optionally set 'WroteCallee' if the callee has already been printed out.
3110bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3111 bool &WroteCallee) {
3112 switch (ID) {
3113 default: {
3114 // If this is an intrinsic that directly corresponds to a GCC
3115 // builtin, we emit it here.
3116 const char *BuiltinName = "";
3117 Function *F = I.getCalledFunction();
3118#define GET_GCC_BUILTIN_NAME
3119#include "llvm/Intrinsics.gen"
3120#undef GET_GCC_BUILTIN_NAME
3121 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3122
3123 Out << BuiltinName;
3124 WroteCallee = true;
3125 return false;
3126 }
3127 case Intrinsic::memory_barrier:
Andrew Lenharth5c976182008-03-05 23:41:37 +00003128 Out << "__sync_synchronize()";
Chris Lattnera74b9182008-03-02 08:29:41 +00003129 return true;
3130 case Intrinsic::vastart:
3131 Out << "0; ";
3132
3133 Out << "va_start(*(va_list*)";
3134 writeOperand(I.getOperand(1));
3135 Out << ", ";
3136 // Output the last argument to the enclosing function.
3137 if (I.getParent()->getParent()->arg_empty()) {
Edwin Török4d9756a2009-07-08 20:53:28 +00003138 std::string msg;
3139 raw_string_ostream Msg(msg);
3140 Msg << "The C backend does not currently support zero "
Chris Lattnera74b9182008-03-02 08:29:41 +00003141 << "argument varargs functions, such as '"
Edwin Török4d9756a2009-07-08 20:53:28 +00003142 << I.getParent()->getParent()->getName() << "'!";
3143 llvm_report_error(Msg.str());
Chris Lattnera74b9182008-03-02 08:29:41 +00003144 }
3145 writeOperand(--I.getParent()->getParent()->arg_end());
3146 Out << ')';
3147 return true;
3148 case Intrinsic::vaend:
3149 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3150 Out << "0; va_end(*(va_list*)";
3151 writeOperand(I.getOperand(1));
3152 Out << ')';
3153 } else {
3154 Out << "va_end(*(va_list*)0)";
3155 }
3156 return true;
3157 case Intrinsic::vacopy:
3158 Out << "0; ";
3159 Out << "va_copy(*(va_list*)";
3160 writeOperand(I.getOperand(1));
3161 Out << ", *(va_list*)";
3162 writeOperand(I.getOperand(2));
3163 Out << ')';
3164 return true;
3165 case Intrinsic::returnaddress:
3166 Out << "__builtin_return_address(";
3167 writeOperand(I.getOperand(1));
3168 Out << ')';
3169 return true;
3170 case Intrinsic::frameaddress:
3171 Out << "__builtin_frame_address(";
3172 writeOperand(I.getOperand(1));
3173 Out << ')';
3174 return true;
3175 case Intrinsic::powi:
3176 Out << "__builtin_powi(";
3177 writeOperand(I.getOperand(1));
3178 Out << ", ";
3179 writeOperand(I.getOperand(2));
3180 Out << ')';
3181 return true;
3182 case Intrinsic::setjmp:
3183 Out << "setjmp(*(jmp_buf*)";
3184 writeOperand(I.getOperand(1));
3185 Out << ')';
3186 return true;
3187 case Intrinsic::longjmp:
3188 Out << "longjmp(*(jmp_buf*)";
3189 writeOperand(I.getOperand(1));
3190 Out << ", ";
3191 writeOperand(I.getOperand(2));
3192 Out << ')';
3193 return true;
3194 case Intrinsic::prefetch:
3195 Out << "LLVM_PREFETCH((const void *)";
3196 writeOperand(I.getOperand(1));
3197 Out << ", ";
3198 writeOperand(I.getOperand(2));
3199 Out << ", ";
3200 writeOperand(I.getOperand(3));
3201 Out << ")";
3202 return true;
3203 case Intrinsic::stacksave:
3204 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3205 // to work around GCC bugs (see PR1809).
3206 Out << "0; *((void**)&" << GetValueName(&I)
3207 << ") = __builtin_stack_save()";
3208 return true;
Chris Lattner6a947cb2008-03-02 08:47:13 +00003209 case Intrinsic::x86_sse_cmp_ss:
3210 case Intrinsic::x86_sse_cmp_ps:
3211 case Intrinsic::x86_sse2_cmp_sd:
3212 case Intrinsic::x86_sse2_cmp_pd:
3213 Out << '(';
3214 printType(Out, I.getType());
3215 Out << ')';
3216 // Multiple GCC builtins multiplex onto this intrinsic.
3217 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003218 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
Chris Lattner6a947cb2008-03-02 08:47:13 +00003219 case 0: Out << "__builtin_ia32_cmpeq"; break;
3220 case 1: Out << "__builtin_ia32_cmplt"; break;
3221 case 2: Out << "__builtin_ia32_cmple"; break;
3222 case 3: Out << "__builtin_ia32_cmpunord"; break;
3223 case 4: Out << "__builtin_ia32_cmpneq"; break;
3224 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3225 case 6: Out << "__builtin_ia32_cmpnle"; break;
3226 case 7: Out << "__builtin_ia32_cmpord"; break;
3227 }
3228 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3229 Out << 'p';
3230 else
3231 Out << 's';
3232 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3233 Out << 's';
3234 else
3235 Out << 'd';
3236
3237 Out << "(";
3238 writeOperand(I.getOperand(1));
3239 Out << ", ";
3240 writeOperand(I.getOperand(2));
3241 Out << ")";
3242 return true;
Chris Lattner709df322008-03-02 08:54:27 +00003243 case Intrinsic::ppc_altivec_lvsl:
3244 Out << '(';
3245 printType(Out, I.getType());
3246 Out << ')';
3247 Out << "__builtin_altivec_lvsl(0, (void*)";
3248 writeOperand(I.getOperand(1));
3249 Out << ")";
3250 return true;
Chris Lattnera74b9182008-03-02 08:29:41 +00003251 }
3252}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003253
3254//This converts the llvm constraint string to something gcc is expecting.
3255//TODO: work out platform independent constraints and factor those out
3256// of the per target tables
3257// handle multiple constraint codes
3258std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003259 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3260
Chris Lattner621c44d2009-08-22 20:48:53 +00003261 // Grab the translation table from MCAsmInfo if it exists.
Chris Lattner63ab9bb2010-01-17 18:22:35 +00003262 const MCAsmInfo *TargetAsm;
3263 std::string Triple = TheModule->getTargetTriple();
3264 if (Triple.empty())
3265 Triple = llvm::sys::getHostTriple();
3266
3267 std::string E;
3268 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3269 TargetAsm = Match->createAsmInfo(Triple);
3270 else
3271 return c.Codes[0];
3272
3273 const char *const *table = TargetAsm->getAsmCBE();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003274
Daniel Dunbarfe5939f2009-07-15 20:24:03 +00003275 // Search the translation table if it exists.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003276 for (int i = 0; table && table[i]; i += 2)
Chris Lattner63ab9bb2010-01-17 18:22:35 +00003277 if (c.Codes[0] == table[i]) {
3278 delete TargetAsm;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003279 return table[i+1];
Chris Lattner63ab9bb2010-01-17 18:22:35 +00003280 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003281
Daniel Dunbarfe5939f2009-07-15 20:24:03 +00003282 // Default is identity.
Chris Lattner63ab9bb2010-01-17 18:22:35 +00003283 delete TargetAsm;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003284 return c.Codes[0];
3285}
3286
3287//TODO: import logic from AsmPrinter.cpp
3288static std::string gccifyAsm(std::string asmstr) {
3289 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3290 if (asmstr[i] == '\n')
3291 asmstr.replace(i, 1, "\\n");
3292 else if (asmstr[i] == '\t')
3293 asmstr.replace(i, 1, "\\t");
3294 else if (asmstr[i] == '$') {
3295 if (asmstr[i + 1] == '{') {
3296 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3297 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3298 std::string n = "%" +
3299 asmstr.substr(a + 1, b - a - 1) +
3300 asmstr.substr(i + 2, a - i - 2);
3301 asmstr.replace(i, b - i + 1, n);
3302 i += n.size() - 1;
3303 } else
3304 asmstr.replace(i, 1, "%");
3305 }
3306 else if (asmstr[i] == '%')//grr
3307 { asmstr.replace(i, 1, "%%"); ++i;}
3308
3309 return asmstr;
3310}
3311
3312//TODO: assumptions about what consume arguments from the call are likely wrong
3313// handle communitivity
3314void CWriter::visitInlineAsm(CallInst &CI) {
3315 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
3316 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
Chris Lattner8a3b6e42008-05-22 06:19:37 +00003317
3318 std::vector<std::pair<Value*, int> > ResultVals;
Owen Anderson35b47072009-08-13 21:58:54 +00003319 if (CI.getType() == Type::getVoidTy(CI.getContext()))
Chris Lattner8a3b6e42008-05-22 06:19:37 +00003320 ;
3321 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3322 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3323 ResultVals.push_back(std::make_pair(&CI, (int)i));
3324 } else {
3325 ResultVals.push_back(std::make_pair(&CI, -1));
3326 }
3327
Chris Lattnera605a9c2008-06-04 18:03:28 +00003328 // Fix up the asm string for gcc and emit it.
3329 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3330 Out << " :";
3331
3332 unsigned ValueCount = 0;
3333 bool IsFirst = true;
3334
3335 // Convert over all the output constraints.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003336 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
Chris Lattnera605a9c2008-06-04 18:03:28 +00003337 E = Constraints.end(); I != E; ++I) {
3338
3339 if (I->Type != InlineAsm::isOutput) {
3340 ++ValueCount;
3341 continue; // Ignore non-output constraints.
3342 }
3343
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003344 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
Chris Lattner8a3b6e42008-05-22 06:19:37 +00003345 std::string C = InterpretASMConstraint(*I);
3346 if (C.empty()) continue;
3347
Chris Lattnera605a9c2008-06-04 18:03:28 +00003348 if (!IsFirst) {
Chris Lattner8a3b6e42008-05-22 06:19:37 +00003349 Out << ", ";
Chris Lattnera605a9c2008-06-04 18:03:28 +00003350 IsFirst = false;
3351 }
3352
3353 // Unpack the dest.
3354 Value *DestVal;
3355 int DestValNo = -1;
3356
3357 if (ValueCount < ResultVals.size()) {
3358 DestVal = ResultVals[ValueCount].first;
3359 DestValNo = ResultVals[ValueCount].second;
3360 } else
3361 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3362
3363 if (I->isEarlyClobber)
3364 C = "&"+C;
3365
3366 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3367 if (DestValNo != -1)
3368 Out << ".field" << DestValNo; // Multiple retvals.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003369 Out << ")";
Chris Lattnera605a9c2008-06-04 18:03:28 +00003370 ++ValueCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003371 }
Chris Lattnera605a9c2008-06-04 18:03:28 +00003372
3373
3374 // Convert over all the input constraints.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003375 Out << "\n :";
Chris Lattnera605a9c2008-06-04 18:03:28 +00003376 IsFirst = true;
3377 ValueCount = 0;
3378 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3379 E = Constraints.end(); I != E; ++I) {
3380 if (I->Type != InlineAsm::isInput) {
3381 ++ValueCount;
3382 continue; // Ignore non-input constraints.
3383 }
3384
3385 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3386 std::string C = InterpretASMConstraint(*I);
3387 if (C.empty()) continue;
3388
3389 if (!IsFirst) {
Chris Lattner5fee1202008-05-22 06:29:38 +00003390 Out << ", ";
Chris Lattnera605a9c2008-06-04 18:03:28 +00003391 IsFirst = false;
3392 }
3393
3394 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3395 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3396
3397 Out << "\"" << C << "\"(";
3398 if (!I->isIndirect)
3399 writeOperand(SrcVal);
3400 else
3401 writeOperandDeref(SrcVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003402 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003403 }
Chris Lattnera605a9c2008-06-04 18:03:28 +00003404
3405 // Convert over the clobber constraints.
3406 IsFirst = true;
Chris Lattnera605a9c2008-06-04 18:03:28 +00003407 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3408 E = Constraints.end(); I != E; ++I) {
3409 if (I->Type != InlineAsm::isClobber)
3410 continue; // Ignore non-input constraints.
3411
3412 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3413 std::string C = InterpretASMConstraint(*I);
3414 if (C.empty()) continue;
3415
3416 if (!IsFirst) {
3417 Out << ", ";
3418 IsFirst = false;
3419 }
3420
3421 Out << '\"' << C << '"';
3422 }
3423
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003424 Out << ")";
3425}
3426
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003427void CWriter::visitAllocaInst(AllocaInst &I) {
3428 Out << '(';
3429 printType(Out, I.getType());
3430 Out << ") alloca(sizeof(";
3431 printType(Out, I.getType()->getElementType());
3432 Out << ')';
3433 if (I.isArrayAllocation()) {
3434 Out << " * " ;
3435 writeOperand(I.getOperand(0));
3436 }
3437 Out << ')';
3438}
3439
Chris Lattner8bbc8592008-03-02 08:07:24 +00003440void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohmanad831302008-07-24 17:57:48 +00003441 gep_type_iterator E, bool Static) {
Chris Lattner8bbc8592008-03-02 08:07:24 +00003442
3443 // If there are no indices, just print out the pointer.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003444 if (I == E) {
Chris Lattner8bbc8592008-03-02 08:07:24 +00003445 writeOperand(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003446 return;
3447 }
Chris Lattner8bbc8592008-03-02 08:07:24 +00003448
3449 // Find out if the last index is into a vector. If so, we have to print this
3450 // specially. Since vectors can't have elements of indexable type, only the
3451 // last index could possibly be of a vector element.
3452 const VectorType *LastIndexIsVector = 0;
3453 {
3454 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3455 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003456 }
Chris Lattner8bbc8592008-03-02 08:07:24 +00003457
3458 Out << "(";
3459
3460 // If the last index is into a vector, we can't print it as &a[i][j] because
3461 // we can't index into a vector with j in GCC. Instead, emit this as
3462 // (((float*)&a[i])+j)
3463 if (LastIndexIsVector) {
3464 Out << "((";
3465 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3466 Out << ")(";
3467 }
3468
3469 Out << '&';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003470
Chris Lattner8bbc8592008-03-02 08:07:24 +00003471 // If the first index is 0 (very typical) we can do a number of
3472 // simplifications to clean up the code.
3473 Value *FirstOp = I.getOperand();
3474 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3475 // First index isn't simple, print it the hard way.
3476 writeOperand(Ptr);
3477 } else {
3478 ++I; // Skip the zero index.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003479
Chris Lattner8bbc8592008-03-02 08:07:24 +00003480 // Okay, emit the first operand. If Ptr is something that is already address
3481 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3482 if (isAddressExposed(Ptr)) {
Dan Gohmanad831302008-07-24 17:57:48 +00003483 writeOperandInternal(Ptr, Static);
Chris Lattner8bbc8592008-03-02 08:07:24 +00003484 } else if (I != E && isa<StructType>(*I)) {
3485 // If we didn't already emit the first operand, see if we can print it as
3486 // P->f instead of "P[0].f"
3487 writeOperand(Ptr);
3488 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3489 ++I; // eat the struct index as well.
3490 } else {
3491 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3492 Out << "(*";
3493 writeOperand(Ptr);
3494 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003495 }
3496 }
3497
Chris Lattner8bbc8592008-03-02 08:07:24 +00003498 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003499 if (isa<StructType>(*I)) {
3500 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
Dan Gohman5d995b02008-06-02 21:30:49 +00003501 } else if (isa<ArrayType>(*I)) {
3502 Out << ".array[";
3503 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3504 Out << ']';
Chris Lattner8bbc8592008-03-02 08:07:24 +00003505 } else if (!isa<VectorType>(*I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003506 Out << '[';
Chris Lattner7ce1ee42007-09-22 20:16:48 +00003507 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003508 Out << ']';
Chris Lattner8bbc8592008-03-02 08:07:24 +00003509 } else {
3510 // If the last index is into a vector, then print it out as "+j)". This
3511 // works with the 'LastIndexIsVector' code above.
3512 if (isa<Constant>(I.getOperand()) &&
3513 cast<Constant>(I.getOperand())->isNullValue()) {
3514 Out << "))"; // avoid "+0".
3515 } else {
3516 Out << ")+(";
3517 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3518 Out << "))";
3519 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003520 }
Chris Lattner8bbc8592008-03-02 08:07:24 +00003521 }
3522 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003523}
3524
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003525void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3526 bool IsVolatile, unsigned Alignment) {
3527
3528 bool IsUnaligned = Alignment &&
3529 Alignment < TD->getABITypeAlignment(OperandType);
3530
3531 if (!IsUnaligned)
3532 Out << '*';
3533 if (IsVolatile || IsUnaligned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003534 Out << "((";
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003535 if (IsUnaligned)
3536 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3537 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3538 if (IsUnaligned) {
3539 Out << "; } ";
3540 if (IsVolatile) Out << "volatile ";
3541 Out << "*";
3542 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003543 Out << ")";
3544 }
3545
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003546 writeOperand(Operand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003547
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003548 if (IsVolatile || IsUnaligned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003549 Out << ')';
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003550 if (IsUnaligned)
3551 Out << "->data";
3552 }
3553}
3554
3555void CWriter::visitLoadInst(LoadInst &I) {
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003556 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3557 I.getAlignment());
3558
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003559}
3560
3561void CWriter::visitStoreInst(StoreInst &I) {
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003562 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3563 I.isVolatile(), I.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003564 Out << " = ";
3565 Value *Operand = I.getOperand(0);
3566 Constant *BitMask = 0;
3567 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3568 if (!ITy->isPowerOf2ByteWidth())
3569 // We have a bit width that doesn't match an even power-of-2 byte
3570 // size. Consequently we must & the value with the type's bit mask
Owen Andersoneacb44d2009-07-24 23:12:02 +00003571 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003572 if (BitMask)
3573 Out << "((";
3574 writeOperand(Operand);
3575 if (BitMask) {
3576 Out << ") & ";
Dan Gohmanad831302008-07-24 17:57:48 +00003577 printConstant(BitMask, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003578 Out << ")";
3579 }
3580}
3581
3582void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner8bbc8592008-03-02 08:07:24 +00003583 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
Dan Gohmanad831302008-07-24 17:57:48 +00003584 gep_type_end(I), false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003585}
3586
3587void CWriter::visitVAArgInst(VAArgInst &I) {
3588 Out << "va_arg(*(va_list*)";
3589 writeOperand(I.getOperand(0));
3590 Out << ", ";
3591 printType(Out, I.getType());
3592 Out << ");\n ";
3593}
3594
Chris Lattnerf41a7942008-03-02 03:52:39 +00003595void CWriter::visitInsertElementInst(InsertElementInst &I) {
3596 const Type *EltTy = I.getType()->getElementType();
3597 writeOperand(I.getOperand(0));
3598 Out << ";\n ";
3599 Out << "((";
3600 printType(Out, PointerType::getUnqual(EltTy));
3601 Out << ")(&" << GetValueName(&I) << "))[";
Chris Lattnerf41a7942008-03-02 03:52:39 +00003602 writeOperand(I.getOperand(2));
Chris Lattner09418362008-03-02 08:10:16 +00003603 Out << "] = (";
3604 writeOperand(I.getOperand(1));
Chris Lattnerf41a7942008-03-02 03:52:39 +00003605 Out << ")";
3606}
3607
Chris Lattnera5f0bc02008-03-02 03:57:08 +00003608void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3609 // We know that our operand is not inlined.
3610 Out << "((";
3611 const Type *EltTy =
3612 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3613 printType(Out, PointerType::getUnqual(EltTy));
3614 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3615 writeOperand(I.getOperand(1));
3616 Out << "]";
3617}
3618
Chris Lattnerf858a042008-03-02 05:41:07 +00003619void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3620 Out << "(";
3621 printType(Out, SVI.getType());
3622 Out << "){ ";
3623 const VectorType *VT = SVI.getType();
3624 unsigned NumElts = VT->getNumElements();
3625 const Type *EltTy = VT->getElementType();
3626
3627 for (unsigned i = 0; i != NumElts; ++i) {
3628 if (i) Out << ", ";
3629 int SrcVal = SVI.getMaskValue(i);
3630 if ((unsigned)SrcVal >= NumElts*2) {
3631 Out << " 0/*undef*/ ";
3632 } else {
3633 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3634 if (isa<Instruction>(Op)) {
3635 // Do an extractelement of this value from the appropriate input.
3636 Out << "((";
3637 printType(Out, PointerType::getUnqual(EltTy));
3638 Out << ")(&" << GetValueName(Op)
Duncan Sandsf6890712008-05-27 11:50:51 +00003639 << "))[" << (SrcVal & (NumElts-1)) << "]";
Chris Lattnerf858a042008-03-02 05:41:07 +00003640 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3641 Out << "0";
3642 } else {
Duncan Sandsf6890712008-05-27 11:50:51 +00003643 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
Dan Gohmanad831302008-07-24 17:57:48 +00003644 (NumElts-1)),
3645 false);
Chris Lattnerf858a042008-03-02 05:41:07 +00003646 }
3647 }
3648 }
3649 Out << "}";
3650}
Chris Lattnera5f0bc02008-03-02 03:57:08 +00003651
Dan Gohman5d995b02008-06-02 21:30:49 +00003652void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3653 // Start by copying the entire aggregate value into the result variable.
3654 writeOperand(IVI.getOperand(0));
3655 Out << ";\n ";
3656
3657 // Then do the insert to update the field.
3658 Out << GetValueName(&IVI);
3659 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3660 i != e; ++i) {
3661 const Type *IndexedTy =
3662 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3663 if (isa<ArrayType>(IndexedTy))
3664 Out << ".array[" << *i << "]";
3665 else
3666 Out << ".field" << *i;
3667 }
3668 Out << " = ";
3669 writeOperand(IVI.getOperand(1));
3670}
3671
3672void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3673 Out << "(";
3674 if (isa<UndefValue>(EVI.getOperand(0))) {
3675 Out << "(";
3676 printType(Out, EVI.getType());
3677 Out << ") 0/*UNDEF*/";
3678 } else {
3679 Out << GetValueName(EVI.getOperand(0));
3680 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3681 i != e; ++i) {
3682 const Type *IndexedTy =
3683 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3684 if (isa<ArrayType>(IndexedTy))
3685 Out << ".array[" << *i << "]";
3686 else
3687 Out << ".field" << *i;
3688 }
3689 }
3690 Out << ")";
3691}
3692
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003693//===----------------------------------------------------------------------===//
3694// External Interface declaration
3695//===----------------------------------------------------------------------===//
3696
3697bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
David Greene302008d2009-07-14 20:18:05 +00003698 formatted_raw_ostream &o,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003699 CodeGenFileType FileType,
Bill Wendling5ed22ac2009-04-29 23:29:43 +00003700 CodeGenOpt::Level OptLevel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003701 if (FileType != TargetMachine::AssemblyFile) return true;
3702
Gordon Henriksendf87fdc2008-01-07 01:30:38 +00003703 PM.add(createGCLoweringPass());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003704 PM.add(createLowerInvokePass());
3705 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3706 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3707 PM.add(new CWriter(o));
Gordon Henriksen1aed5992008-08-17 18:44:35 +00003708 PM.add(createGCInfoDeleter());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003709 return false;
3710}