blob: 1eeee99151c8072c1cc38f2d77884bee8dd9e369 [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"
27#include "llvm/Analysis/ConstantsScanner.h"
28#include "llvm/Analysis/FindUsedTypes.h"
29#include "llvm/Analysis/LoopInfo.h"
Gordon Henriksendf87fdc2008-01-07 01:30:38 +000030#include "llvm/CodeGen/Passes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/CodeGen/IntrinsicLowering.h"
32#include "llvm/Transforms/Scalar.h"
33#include "llvm/Target/TargetMachineRegistry.h"
34#include "llvm/Target/TargetAsmInfo.h"
35#include "llvm/Target/TargetData.h"
36#include "llvm/Support/CallSite.h"
37#include "llvm/Support/CFG.h"
Edwin Török4d9756a2009-07-08 20:53:28 +000038#include "llvm/Support/ErrorHandling.h"
David Greene302008d2009-07-14 20:18:05 +000039#include "llvm/Support/FormattedStream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/Support/GetElementPtrTypeIterator.h"
41#include "llvm/Support/InstVisitor.h"
42#include "llvm/Support/Mangler.h"
43#include "llvm/Support/MathExtras.h"
44#include "llvm/ADT/StringExtras.h"
45#include "llvm/ADT/STLExtras.h"
46#include "llvm/Support/MathExtras.h"
47#include "llvm/Config/config.h"
48#include <algorithm>
49#include <sstream>
50using namespace llvm;
51
Oscar Fuentes4f012352008-11-15 21:36:30 +000052/// CBackendTargetMachineModule - Note that this is used on hosts that
53/// cannot link in a library unless there are references into the
54/// library. In particular, it seems that it is not possible to get
55/// things to work on Win32 without this. Though it is unused, do not
56/// remove it.
57extern "C" int CBackendTargetMachineModule;
58int CBackendTargetMachineModule = 0;
59
Dan Gohman089efff2008-05-13 00:00:25 +000060// Register the target.
Daniel Dunbar6fa4f572009-07-15 09:22:31 +000061extern Target TheCBackendTarget;
62static RegisterTarget<CTargetMachine> X(TheCBackendTarget, "c", "C backend");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000063
Bob Wilsonebbc1c42009-06-23 23:59:40 +000064// Force static initialization.
65extern "C" void LLVMInitializeCBackendTarget() { }
Douglas Gregor1dc5ff42009-06-16 20:12:29 +000066
Dan Gohman089efff2008-05-13 00:00:25 +000067namespace {
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;
98 const TargetAsmInfo* TAsm;
99 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.
248 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
249 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);
294 void visitInvokeInst(InvokeInst &I) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000295 llvm_unreachable("Lowerinvoke pass didn't work!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 }
297
298 void visitUnwindInst(UnwindInst &I) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000299 llvm_unreachable("Lowerinvoke pass didn't work!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300 }
301 void visitUnreachableInst(UnreachableInst &I);
302
303 void visitPHINode(PHINode &I);
304 void visitBinaryOperator(Instruction &I);
305 void visitICmpInst(ICmpInst &I);
306 void visitFCmpInst(FCmpInst &I);
307
308 void visitCastInst (CastInst &I);
309 void visitSelectInst(SelectInst &I);
310 void visitCallInst (CallInst &I);
311 void visitInlineAsm(CallInst &I);
Chris Lattnera74b9182008-03-02 08:29:41 +0000312 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313
314 void visitMallocInst(MallocInst &I);
315 void visitAllocaInst(AllocaInst &I);
316 void visitFreeInst (FreeInst &I);
317 void visitLoadInst (LoadInst &I);
318 void visitStoreInst (StoreInst &I);
319 void visitGetElementPtrInst(GetElementPtrInst &I);
320 void visitVAArgInst (VAArgInst &I);
Chris Lattnerf41a7942008-03-02 03:52:39 +0000321
322 void visitInsertElementInst(InsertElementInst &I);
Chris Lattnera5f0bc02008-03-02 03:57:08 +0000323 void visitExtractElementInst(ExtractElementInst &I);
Chris Lattnerf858a042008-03-02 05:41:07 +0000324 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325
Dan Gohman5d995b02008-06-02 21:30:49 +0000326 void visitInsertValueInst(InsertValueInst &I);
327 void visitExtractValueInst(ExtractValueInst &I);
328
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329 void visitInstruction(Instruction &I) {
Edwin Török4d9756a2009-07-08 20:53:28 +0000330#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331 cerr << "C Writer does not know about " << I;
Edwin Török4d9756a2009-07-08 20:53:28 +0000332#endif
Edwin Törökbd448e32009-07-14 16:55:14 +0000333 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334 }
335
336 void outputLValue(Instruction *I) {
337 Out << " " << GetValueName(I) << " = ";
338 }
339
340 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
341 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
342 BasicBlock *Successor, unsigned Indent);
343 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
344 unsigned Indent);
Chris Lattner8bbc8592008-03-02 08:07:24 +0000345 void printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohmanad831302008-07-24 17:57:48 +0000346 gep_type_iterator E, bool Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347
348 std::string GetValueName(const Value *Operand);
349 };
350}
351
352char CWriter::ID = 0;
353
354/// This method inserts names for any unnamed structure types that are used by
355/// the program, and removes names from structure types that are not used by the
356/// program.
357///
358bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
359 // Get a set of types that are used by the program...
360 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
361
362 // Loop over the module symbol table, removing types from UT that are
363 // already named, and removing names for types that are not used.
364 //
365 TypeSymbolTable &TST = M.getTypeSymbolTable();
366 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
367 TI != TE; ) {
368 TypeSymbolTable::iterator I = TI++;
369
Dan Gohman5d995b02008-06-02 21:30:49 +0000370 // If this isn't a struct or array type, remove it from our set of types
371 // to name. This simplifies emission later.
372 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
373 !isa<ArrayType>(I->second)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000374 TST.remove(I);
375 } else {
376 // If this is not used, remove it from the symbol table.
377 std::set<const Type *>::iterator UTI = UT.find(I->second);
378 if (UTI == UT.end())
379 TST.remove(I);
380 else
381 UT.erase(UTI); // Only keep one name for this type.
382 }
383 }
384
385 // UT now contains types that are not named. Loop over it, naming
386 // structure types.
387 //
388 bool Changed = false;
389 unsigned RenameCounter = 0;
390 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
391 I != E; ++I)
Dan Gohman5d995b02008-06-02 21:30:49 +0000392 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
393 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000394 ++RenameCounter;
395 Changed = true;
396 }
397
398
399 // Loop over all external functions and globals. If we have two with
400 // identical names, merge them.
401 // FIXME: This code should disappear when we don't allow values with the same
402 // names when they have different types!
403 std::map<std::string, GlobalValue*> ExtSymbols;
404 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
405 Function *GV = I++;
406 if (GV->isDeclaration() && GV->hasName()) {
407 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
408 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
409 if (!X.second) {
410 // Found a conflict, replace this global with the previous one.
411 GlobalValue *OldGV = X.first->second;
412 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
413 GV->eraseFromParent();
414 Changed = true;
415 }
416 }
417 }
418 // Do the same for globals.
419 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
420 I != E;) {
421 GlobalVariable *GV = I++;
422 if (GV->isDeclaration() && GV->hasName()) {
423 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
424 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
425 if (!X.second) {
426 // Found a conflict, replace this global with the previous one.
427 GlobalValue *OldGV = X.first->second;
428 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
429 GV->eraseFromParent();
430 Changed = true;
431 }
432 }
433 }
434
435 return Changed;
436}
437
438/// printStructReturnPointerFunctionType - This is like printType for a struct
439/// return type, except, instead of printing the type as void (*)(Struct*, ...)
440/// print it as "Struct (*)(...)", for struct return functions.
David Greene302008d2009-07-14 20:18:05 +0000441void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
Devang Pateld222f862008-09-25 21:00:45 +0000442 const AttrListPtr &PAL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443 const PointerType *TheTy) {
444 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
445 std::stringstream FunctionInnards;
446 FunctionInnards << " (*) (";
447 bool PrintedType = false;
448
449 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
450 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
451 unsigned Idx = 1;
Evan Cheng2054cb02008-01-11 03:07:46 +0000452 for (++I, ++Idx; I != E; ++I, ++Idx) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000453 if (PrintedType)
454 FunctionInnards << ", ";
Evan Cheng2054cb02008-01-11 03:07:46 +0000455 const Type *ArgTy = *I;
Devang Pateld222f862008-09-25 21:00:45 +0000456 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng17254e62008-01-11 09:12:49 +0000457 assert(isa<PointerType>(ArgTy));
458 ArgTy = cast<PointerType>(ArgTy)->getElementType();
459 }
Evan Cheng2054cb02008-01-11 03:07:46 +0000460 printType(FunctionInnards, ArgTy,
Devang Pateld222f862008-09-25 21:00:45 +0000461 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000462 PrintedType = true;
463 }
464 if (FTy->isVarArg()) {
465 if (PrintedType)
466 FunctionInnards << ", ...";
467 } else if (!PrintedType) {
468 FunctionInnards << "void";
469 }
470 FunctionInnards << ')';
471 std::string tstr = FunctionInnards.str();
472 printType(Out, RetTy,
Devang Pateld222f862008-09-25 21:00:45 +0000473 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474}
475
Owen Anderson847b99b2008-08-21 00:14:44 +0000476raw_ostream &
David Greene302008d2009-07-14 20:18:05 +0000477CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
478 bool isSigned,
Owen Anderson847b99b2008-08-21 00:14:44 +0000479 const std::string &NameSoFar) {
480 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
481 "Invalid type for printSimpleType");
482 switch (Ty->getTypeID()) {
483 case Type::VoidTyID: return Out << "void " << NameSoFar;
484 case Type::IntegerTyID: {
485 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
486 if (NumBits == 1)
487 return Out << "bool " << NameSoFar;
488 else if (NumBits <= 8)
489 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
490 else if (NumBits <= 16)
491 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
492 else if (NumBits <= 32)
493 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
494 else if (NumBits <= 64)
495 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
496 else {
497 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
498 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
499 }
500 }
501 case Type::FloatTyID: return Out << "float " << NameSoFar;
502 case Type::DoubleTyID: return Out << "double " << NameSoFar;
503 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
504 // present matches host 'long double'.
505 case Type::X86_FP80TyID:
506 case Type::PPC_FP128TyID:
507 case Type::FP128TyID: return Out << "long double " << NameSoFar;
508
509 case Type::VectorTyID: {
510 const VectorType *VTy = cast<VectorType>(Ty);
511 return printSimpleType(Out, VTy->getElementType(), isSigned,
512 " __attribute__((vector_size(" +
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000513 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Owen Anderson847b99b2008-08-21 00:14:44 +0000514 }
515
516 default:
Edwin Török4d9756a2009-07-08 20:53:28 +0000517#ifndef NDEBUG
Owen Anderson847b99b2008-08-21 00:14:44 +0000518 cerr << "Unknown primitive type: " << *Ty << "\n";
Edwin Török4d9756a2009-07-08 20:53:28 +0000519#endif
Edwin Törökbd448e32009-07-14 16:55:14 +0000520 llvm_unreachable(0);
Owen Anderson847b99b2008-08-21 00:14:44 +0000521 }
522}
523
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000524std::ostream &
525CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
Chris Lattnerd8090712008-03-02 03:41:23 +0000526 const std::string &NameSoFar) {
Chris Lattnerdb6d5ce2008-03-02 03:33:31 +0000527 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528 "Invalid type for printSimpleType");
529 switch (Ty->getTypeID()) {
530 case Type::VoidTyID: return Out << "void " << NameSoFar;
531 case Type::IntegerTyID: {
532 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
533 if (NumBits == 1)
534 return Out << "bool " << NameSoFar;
535 else if (NumBits <= 8)
536 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
537 else if (NumBits <= 16)
538 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
539 else if (NumBits <= 32)
540 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
Dan Gohmana2245af2008-04-02 19:40:14 +0000541 else if (NumBits <= 64)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000542 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
Dan Gohmana2245af2008-04-02 19:40:14 +0000543 else {
544 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
545 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000546 }
547 }
548 case Type::FloatTyID: return Out << "float " << NameSoFar;
549 case Type::DoubleTyID: return Out << "double " << NameSoFar;
Dale Johannesen137cef62007-09-17 00:38:27 +0000550 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
551 // present matches host 'long double'.
552 case Type::X86_FP80TyID:
553 case Type::PPC_FP128TyID:
554 case Type::FP128TyID: return Out << "long double " << NameSoFar;
Chris Lattnerdb6d5ce2008-03-02 03:33:31 +0000555
556 case Type::VectorTyID: {
557 const VectorType *VTy = cast<VectorType>(Ty);
Chris Lattnerd8090712008-03-02 03:41:23 +0000558 return printSimpleType(Out, VTy->getElementType(), isSigned,
Chris Lattnerfddca552008-03-02 03:39:43 +0000559 " __attribute__((vector_size(" +
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000560 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Chris Lattnerdb6d5ce2008-03-02 03:33:31 +0000561 }
562
563 default:
Edwin Török4d9756a2009-07-08 20:53:28 +0000564#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565 cerr << "Unknown primitive type: " << *Ty << "\n";
Edwin Török4d9756a2009-07-08 20:53:28 +0000566#endif
Edwin Törökbd448e32009-07-14 16:55:14 +0000567 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000568 }
569}
570
571// Pass the Type* and the variable name and this prints out the variable
572// declaration.
573//
David Greene302008d2009-07-14 20:18:05 +0000574raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
575 const Type *Ty,
576 bool isSigned, const std::string &NameSoFar,
577 bool IgnoreName, const AttrListPtr &PAL) {
Owen Anderson847b99b2008-08-21 00:14:44 +0000578 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
579 printSimpleType(Out, Ty, isSigned, NameSoFar);
580 return Out;
581 }
582
583 // Check to see if the type is named.
584 if (!IgnoreName || isa<OpaqueType>(Ty)) {
585 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
586 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
587 }
588
589 switch (Ty->getTypeID()) {
590 case Type::FunctionTyID: {
591 const FunctionType *FTy = cast<FunctionType>(Ty);
592 std::stringstream FunctionInnards;
593 FunctionInnards << " (" << NameSoFar << ") (";
594 unsigned Idx = 1;
595 for (FunctionType::param_iterator I = FTy->param_begin(),
596 E = FTy->param_end(); I != E; ++I) {
597 const Type *ArgTy = *I;
Devang Pateld222f862008-09-25 21:00:45 +0000598 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Owen Anderson847b99b2008-08-21 00:14:44 +0000599 assert(isa<PointerType>(ArgTy));
600 ArgTy = cast<PointerType>(ArgTy)->getElementType();
601 }
602 if (I != FTy->param_begin())
603 FunctionInnards << ", ";
604 printType(FunctionInnards, ArgTy,
Devang Pateld222f862008-09-25 21:00:45 +0000605 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Owen Anderson847b99b2008-08-21 00:14:44 +0000606 ++Idx;
607 }
608 if (FTy->isVarArg()) {
609 if (FTy->getNumParams())
610 FunctionInnards << ", ...";
611 } else if (!FTy->getNumParams()) {
612 FunctionInnards << "void";
613 }
614 FunctionInnards << ')';
615 std::string tstr = FunctionInnards.str();
616 printType(Out, FTy->getReturnType(),
Devang Pateld222f862008-09-25 21:00:45 +0000617 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Owen Anderson847b99b2008-08-21 00:14:44 +0000618 return Out;
619 }
620 case Type::StructTyID: {
621 const StructType *STy = cast<StructType>(Ty);
622 Out << NameSoFar + " {\n";
623 unsigned Idx = 0;
624 for (StructType::element_iterator I = STy->element_begin(),
625 E = STy->element_end(); I != E; ++I) {
626 Out << " ";
627 printType(Out, *I, false, "field" + utostr(Idx++));
628 Out << ";\n";
629 }
630 Out << '}';
631 if (STy->isPacked())
632 Out << " __attribute__ ((packed))";
633 return Out;
634 }
635
636 case Type::PointerTyID: {
637 const PointerType *PTy = cast<PointerType>(Ty);
638 std::string ptrName = "*" + NameSoFar;
639
640 if (isa<ArrayType>(PTy->getElementType()) ||
641 isa<VectorType>(PTy->getElementType()))
642 ptrName = "(" + ptrName + ")";
643
644 if (!PAL.isEmpty())
645 // Must be a function ptr cast!
646 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
647 return printType(Out, PTy->getElementType(), false, ptrName);
648 }
649
650 case Type::ArrayTyID: {
651 const ArrayType *ATy = cast<ArrayType>(Ty);
652 unsigned NumElements = ATy->getNumElements();
653 if (NumElements == 0) NumElements = 1;
654 // Arrays are wrapped in structs to allow them to have normal
655 // value semantics (avoiding the array "decay").
656 Out << NameSoFar << " { ";
657 printType(Out, ATy->getElementType(), false,
658 "array[" + utostr(NumElements) + "]");
659 return Out << "; }";
660 }
661
662 case Type::OpaqueTyID: {
Owen Andersonde8a9442009-06-26 19:48:37 +0000663 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Owen Anderson847b99b2008-08-21 00:14:44 +0000664 assert(TypeNames.find(Ty) == TypeNames.end());
665 TypeNames[Ty] = TyName;
666 return Out << TyName << ' ' << NameSoFar;
667 }
668 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000669 llvm_unreachable("Unhandled case in getTypeProps!");
Owen Anderson847b99b2008-08-21 00:14:44 +0000670 }
671
672 return Out;
673}
674
675// Pass the Type* and the variable name and this prints out the variable
676// declaration.
677//
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000678std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
679 bool isSigned, const std::string &NameSoFar,
Devang Pateld222f862008-09-25 21:00:45 +0000680 bool IgnoreName, const AttrListPtr &PAL) {
Chris Lattnerdb6d5ce2008-03-02 03:33:31 +0000681 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682 printSimpleType(Out, Ty, isSigned, NameSoFar);
683 return Out;
684 }
685
686 // Check to see if the type is named.
687 if (!IgnoreName || isa<OpaqueType>(Ty)) {
688 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
689 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
690 }
691
692 switch (Ty->getTypeID()) {
693 case Type::FunctionTyID: {
694 const FunctionType *FTy = cast<FunctionType>(Ty);
695 std::stringstream FunctionInnards;
696 FunctionInnards << " (" << NameSoFar << ") (";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000697 unsigned Idx = 1;
698 for (FunctionType::param_iterator I = FTy->param_begin(),
699 E = FTy->param_end(); I != E; ++I) {
Evan Chengb8a072c2008-01-12 18:53:07 +0000700 const Type *ArgTy = *I;
Devang Pateld222f862008-09-25 21:00:45 +0000701 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Chengb8a072c2008-01-12 18:53:07 +0000702 assert(isa<PointerType>(ArgTy));
703 ArgTy = cast<PointerType>(ArgTy)->getElementType();
704 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705 if (I != FTy->param_begin())
706 FunctionInnards << ", ";
Evan Chengb8a072c2008-01-12 18:53:07 +0000707 printType(FunctionInnards, ArgTy,
Devang Pateld222f862008-09-25 21:00:45 +0000708 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000709 ++Idx;
710 }
711 if (FTy->isVarArg()) {
712 if (FTy->getNumParams())
713 FunctionInnards << ", ...";
714 } else if (!FTy->getNumParams()) {
715 FunctionInnards << "void";
716 }
717 FunctionInnards << ')';
718 std::string tstr = FunctionInnards.str();
719 printType(Out, FTy->getReturnType(),
Devang Pateld222f862008-09-25 21:00:45 +0000720 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 return Out;
722 }
723 case Type::StructTyID: {
724 const StructType *STy = cast<StructType>(Ty);
725 Out << NameSoFar + " {\n";
726 unsigned Idx = 0;
727 for (StructType::element_iterator I = STy->element_begin(),
728 E = STy->element_end(); I != E; ++I) {
729 Out << " ";
730 printType(Out, *I, false, "field" + utostr(Idx++));
731 Out << ";\n";
732 }
733 Out << '}';
734 if (STy->isPacked())
735 Out << " __attribute__ ((packed))";
736 return Out;
737 }
738
739 case Type::PointerTyID: {
740 const PointerType *PTy = cast<PointerType>(Ty);
741 std::string ptrName = "*" + NameSoFar;
742
743 if (isa<ArrayType>(PTy->getElementType()) ||
744 isa<VectorType>(PTy->getElementType()))
745 ptrName = "(" + ptrName + ")";
746
Chris Lattner1c8733e2008-03-12 17:45:29 +0000747 if (!PAL.isEmpty())
Evan Chengb8a072c2008-01-12 18:53:07 +0000748 // Must be a function ptr cast!
749 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000750 return printType(Out, PTy->getElementType(), false, ptrName);
751 }
752
753 case Type::ArrayTyID: {
754 const ArrayType *ATy = cast<ArrayType>(Ty);
755 unsigned NumElements = ATy->getNumElements();
756 if (NumElements == 0) NumElements = 1;
Dan Gohman5d995b02008-06-02 21:30:49 +0000757 // Arrays are wrapped in structs to allow them to have normal
758 // value semantics (avoiding the array "decay").
759 Out << NameSoFar << " { ";
760 printType(Out, ATy->getElementType(), false,
761 "array[" + utostr(NumElements) + "]");
762 return Out << "; }";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000763 }
764
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000765 case Type::OpaqueTyID: {
Owen Andersonde8a9442009-06-26 19:48:37 +0000766 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767 assert(TypeNames.find(Ty) == TypeNames.end());
768 TypeNames[Ty] = TyName;
769 return Out << TyName << ' ' << NameSoFar;
770 }
771 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000772 llvm_unreachable("Unhandled case in getTypeProps!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773 }
774
775 return Out;
776}
777
Dan Gohmanad831302008-07-24 17:57:48 +0000778void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000779
780 // As a special case, print the array as a string if it is an array of
781 // ubytes or an array of sbytes with positive values.
782 //
783 const Type *ETy = CPA->getType()->getElementType();
784 bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty);
785
786 // Make sure the last character is a null char, as automatically added by C
787 if (isString && (CPA->getNumOperands() == 0 ||
788 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
789 isString = false;
790
791 if (isString) {
792 Out << '\"';
793 // Keep track of whether the last number was a hexadecimal escape
794 bool LastWasHex = false;
795
796 // Do not include the last character, which we know is null
797 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
798 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
799
800 // Print it out literally if it is a printable character. The only thing
801 // to be careful about is when the last letter output was a hex escape
802 // code, in which case we have to be careful not to print out hex digits
803 // explicitly (the C compiler thinks it is a continuation of the previous
804 // character, sheesh...)
805 //
806 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
807 LastWasHex = false;
808 if (C == '"' || C == '\\')
Chris Lattner009f3962008-08-21 05:51:43 +0000809 Out << "\\" << (char)C;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000810 else
Chris Lattner009f3962008-08-21 05:51:43 +0000811 Out << (char)C;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000812 } else {
813 LastWasHex = false;
814 switch (C) {
815 case '\n': Out << "\\n"; break;
816 case '\t': Out << "\\t"; break;
817 case '\r': Out << "\\r"; break;
818 case '\v': Out << "\\v"; break;
819 case '\a': Out << "\\a"; break;
820 case '\"': Out << "\\\""; break;
821 case '\'': Out << "\\\'"; break;
822 default:
823 Out << "\\x";
824 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
825 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
826 LastWasHex = true;
827 break;
828 }
829 }
830 }
831 Out << '\"';
832 } else {
833 Out << '{';
834 if (CPA->getNumOperands()) {
835 Out << ' ';
Dan Gohmanad831302008-07-24 17:57:48 +0000836 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000837 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
838 Out << ", ";
Dan Gohmanad831302008-07-24 17:57:48 +0000839 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000840 }
841 }
842 Out << " }";
843 }
844}
845
Dan Gohmanad831302008-07-24 17:57:48 +0000846void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847 Out << '{';
848 if (CP->getNumOperands()) {
849 Out << ' ';
Dan Gohmanad831302008-07-24 17:57:48 +0000850 printConstant(cast<Constant>(CP->getOperand(0)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
852 Out << ", ";
Dan Gohmanad831302008-07-24 17:57:48 +0000853 printConstant(cast<Constant>(CP->getOperand(i)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000854 }
855 }
856 Out << " }";
857}
858
859// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
860// textually as a double (rather than as a reference to a stack-allocated
861// variable). We decide this by converting CFP to a string and back into a
862// double, and then checking whether the conversion results in a bit-equal
863// double to the original value of CFP. This depends on us and the target C
864// compiler agreeing on the conversion process (which is pretty likely since we
865// only deal in IEEE FP).
866//
867static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Dale Johannesen6e547b42008-10-09 23:00:39 +0000868 bool ignored;
Dale Johannesen137cef62007-09-17 00:38:27 +0000869 // Do long doubles in hex for now.
Chris Lattnerf6e12012008-10-22 04:53:16 +0000870 if (CFP->getType() != Type::FloatTy && CFP->getType() != Type::DoubleTy)
Dale Johannesen2fc20782007-09-14 22:26:36 +0000871 return false;
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000872 APFloat APF = APFloat(CFP->getValueAPF()); // copy
Chris Lattnerf6e12012008-10-22 04:53:16 +0000873 if (CFP->getType() == Type::FloatTy)
Dale Johannesen6e547b42008-10-09 23:00:39 +0000874 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
876 char Buffer[100];
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000877 sprintf(Buffer, "%a", APF.convertToDouble());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000878 if (!strncmp(Buffer, "0x", 2) ||
879 !strncmp(Buffer, "-0x", 3) ||
880 !strncmp(Buffer, "+0x", 3))
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000881 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000882 return false;
883#else
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000884 std::string StrVal = ftostr(APF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000885
886 while (StrVal[0] == ' ')
887 StrVal.erase(StrVal.begin());
888
889 // Check to make sure that the stringized number is not some string like "Inf"
890 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
891 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
892 ((StrVal[0] == '-' || StrVal[0] == '+') &&
893 (StrVal[1] >= '0' && StrVal[1] <= '9')))
894 // Reparse stringized version!
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000895 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000896 return false;
897#endif
898}
899
900/// Print out the casting for a cast operation. This does the double casting
901/// necessary for conversion to the destination type, if necessary.
902/// @brief Print a cast
903void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
904 // Print the destination type cast
905 switch (opc) {
906 case Instruction::UIToFP:
907 case Instruction::SIToFP:
908 case Instruction::IntToPtr:
909 case Instruction::Trunc:
910 case Instruction::BitCast:
911 case Instruction::FPExt:
912 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
913 Out << '(';
914 printType(Out, DstTy);
915 Out << ')';
916 break;
917 case Instruction::ZExt:
918 case Instruction::PtrToInt:
919 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
920 Out << '(';
921 printSimpleType(Out, DstTy, false);
922 Out << ')';
923 break;
924 case Instruction::SExt:
925 case Instruction::FPToSI: // For these, make sure we get a signed dest
926 Out << '(';
927 printSimpleType(Out, DstTy, true);
928 Out << ')';
929 break;
930 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000931 llvm_unreachable("Invalid cast opcode");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000932 }
933
934 // Print the source type cast
935 switch (opc) {
936 case Instruction::UIToFP:
937 case Instruction::ZExt:
938 Out << '(';
939 printSimpleType(Out, SrcTy, false);
940 Out << ')';
941 break;
942 case Instruction::SIToFP:
943 case Instruction::SExt:
944 Out << '(';
945 printSimpleType(Out, SrcTy, true);
946 Out << ')';
947 break;
948 case Instruction::IntToPtr:
949 case Instruction::PtrToInt:
950 // Avoid "cast to pointer from integer of different size" warnings
951 Out << "(unsigned long)";
952 break;
953 case Instruction::Trunc:
954 case Instruction::BitCast:
955 case Instruction::FPExt:
956 case Instruction::FPTrunc:
957 case Instruction::FPToSI:
958 case Instruction::FPToUI:
959 break; // These don't need a source cast.
960 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000961 llvm_unreachable("Invalid cast opcode");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962 break;
963 }
964}
965
966// printConstant - The LLVM Constant to C Constant converter.
Dan Gohmanad831302008-07-24 17:57:48 +0000967void CWriter::printConstant(Constant *CPV, bool Static) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000968 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
969 switch (CE->getOpcode()) {
970 case Instruction::Trunc:
971 case Instruction::ZExt:
972 case Instruction::SExt:
973 case Instruction::FPTrunc:
974 case Instruction::FPExt:
975 case Instruction::UIToFP:
976 case Instruction::SIToFP:
977 case Instruction::FPToUI:
978 case Instruction::FPToSI:
979 case Instruction::PtrToInt:
980 case Instruction::IntToPtr:
981 case Instruction::BitCast:
982 Out << "(";
983 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
984 if (CE->getOpcode() == Instruction::SExt &&
985 CE->getOperand(0)->getType() == Type::Int1Ty) {
986 // Make sure we really sext from bool here by subtracting from 0
987 Out << "0-";
988 }
Dan Gohmanad831302008-07-24 17:57:48 +0000989 printConstant(CE->getOperand(0), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000990 if (CE->getType() == Type::Int1Ty &&
991 (CE->getOpcode() == Instruction::Trunc ||
992 CE->getOpcode() == Instruction::FPToUI ||
993 CE->getOpcode() == Instruction::FPToSI ||
994 CE->getOpcode() == Instruction::PtrToInt)) {
995 // Make sure we really truncate to bool here by anding with 1
996 Out << "&1u";
997 }
998 Out << ')';
999 return;
1000
1001 case Instruction::GetElementPtr:
Chris Lattner8bbc8592008-03-02 08:07:24 +00001002 Out << "(";
1003 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
Dan Gohmanad831302008-07-24 17:57:48 +00001004 gep_type_end(CPV), Static);
Chris Lattner8bbc8592008-03-02 08:07:24 +00001005 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006 return;
1007 case Instruction::Select:
1008 Out << '(';
Dan Gohmanad831302008-07-24 17:57:48 +00001009 printConstant(CE->getOperand(0), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001010 Out << '?';
Dan Gohmanad831302008-07-24 17:57:48 +00001011 printConstant(CE->getOperand(1), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012 Out << ':';
Dan Gohmanad831302008-07-24 17:57:48 +00001013 printConstant(CE->getOperand(2), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014 Out << ')';
1015 return;
1016 case Instruction::Add:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001017 case Instruction::FAdd:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001018 case Instruction::Sub:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001019 case Instruction::FSub:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020 case Instruction::Mul:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001021 case Instruction::FMul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001022 case Instruction::SDiv:
1023 case Instruction::UDiv:
1024 case Instruction::FDiv:
1025 case Instruction::URem:
1026 case Instruction::SRem:
1027 case Instruction::FRem:
1028 case Instruction::And:
1029 case Instruction::Or:
1030 case Instruction::Xor:
1031 case Instruction::ICmp:
1032 case Instruction::Shl:
1033 case Instruction::LShr:
1034 case Instruction::AShr:
1035 {
1036 Out << '(';
Dan Gohmanad831302008-07-24 17:57:48 +00001037 bool NeedsClosingParens = printConstExprCast(CE, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001038 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1039 switch (CE->getOpcode()) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00001040 case Instruction::Add:
1041 case Instruction::FAdd: Out << " + "; break;
1042 case Instruction::Sub:
1043 case Instruction::FSub: Out << " - "; break;
1044 case Instruction::Mul:
1045 case Instruction::FMul: Out << " * "; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046 case Instruction::URem:
1047 case Instruction::SRem:
1048 case Instruction::FRem: Out << " % "; break;
1049 case Instruction::UDiv:
1050 case Instruction::SDiv:
1051 case Instruction::FDiv: Out << " / "; break;
1052 case Instruction::And: Out << " & "; break;
1053 case Instruction::Or: Out << " | "; break;
1054 case Instruction::Xor: Out << " ^ "; break;
1055 case Instruction::Shl: Out << " << "; break;
1056 case Instruction::LShr:
1057 case Instruction::AShr: Out << " >> "; break;
1058 case Instruction::ICmp:
1059 switch (CE->getPredicate()) {
1060 case ICmpInst::ICMP_EQ: Out << " == "; break;
1061 case ICmpInst::ICMP_NE: Out << " != "; break;
1062 case ICmpInst::ICMP_SLT:
1063 case ICmpInst::ICMP_ULT: Out << " < "; break;
1064 case ICmpInst::ICMP_SLE:
1065 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1066 case ICmpInst::ICMP_SGT:
1067 case ICmpInst::ICMP_UGT: Out << " > "; break;
1068 case ICmpInst::ICMP_SGE:
1069 case ICmpInst::ICMP_UGE: Out << " >= "; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00001070 default: llvm_unreachable("Illegal ICmp predicate");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071 }
1072 break;
Edwin Törökbd448e32009-07-14 16:55:14 +00001073 default: llvm_unreachable("Illegal opcode here!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001074 }
1075 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1076 if (NeedsClosingParens)
1077 Out << "))";
1078 Out << ')';
1079 return;
1080 }
1081 case Instruction::FCmp: {
1082 Out << '(';
Dan Gohmanad831302008-07-24 17:57:48 +00001083 bool NeedsClosingParens = printConstExprCast(CE, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001084 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1085 Out << "0";
1086 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1087 Out << "1";
1088 else {
1089 const char* op = 0;
1090 switch (CE->getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001091 default: llvm_unreachable("Illegal FCmp predicate");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001092 case FCmpInst::FCMP_ORD: op = "ord"; break;
1093 case FCmpInst::FCMP_UNO: op = "uno"; break;
1094 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1095 case FCmpInst::FCMP_UNE: op = "une"; break;
1096 case FCmpInst::FCMP_ULT: op = "ult"; break;
1097 case FCmpInst::FCMP_ULE: op = "ule"; break;
1098 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1099 case FCmpInst::FCMP_UGE: op = "uge"; break;
1100 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1101 case FCmpInst::FCMP_ONE: op = "one"; break;
1102 case FCmpInst::FCMP_OLT: op = "olt"; break;
1103 case FCmpInst::FCMP_OLE: op = "ole"; break;
1104 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1105 case FCmpInst::FCMP_OGE: op = "oge"; break;
1106 }
1107 Out << "llvm_fcmp_" << op << "(";
1108 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1109 Out << ", ";
1110 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1111 Out << ")";
1112 }
1113 if (NeedsClosingParens)
1114 Out << "))";
1115 Out << ')';
Anton Korobeynikov44891ce2007-12-21 23:33:44 +00001116 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001117 }
1118 default:
Edwin Török4d9756a2009-07-08 20:53:28 +00001119#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120 cerr << "CWriter Error: Unhandled constant expression: "
1121 << *CE << "\n";
Edwin Török4d9756a2009-07-08 20:53:28 +00001122#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001123 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124 }
Dan Gohman76c2cb42008-05-23 16:57:00 +00001125 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001126 Out << "((";
1127 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnerc72d9e32008-03-02 08:14:45 +00001128 Out << ")/*UNDEF*/";
1129 if (!isa<VectorType>(CPV->getType())) {
1130 Out << "0)";
1131 } else {
1132 Out << "{})";
1133 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001134 return;
1135 }
1136
1137 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1138 const Type* Ty = CI->getType();
1139 if (Ty == Type::Int1Ty)
Chris Lattner63fb1f02008-03-02 03:16:38 +00001140 Out << (CI->getZExtValue() ? '1' : '0');
1141 else if (Ty == Type::Int32Ty)
1142 Out << CI->getZExtValue() << 'u';
1143 else if (Ty->getPrimitiveSizeInBits() > 32)
1144 Out << CI->getZExtValue() << "ull";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001145 else {
1146 Out << "((";
1147 printSimpleType(Out, Ty, false) << ')';
1148 if (CI->isMinValue(true))
1149 Out << CI->getZExtValue() << 'u';
1150 else
1151 Out << CI->getSExtValue();
Dale Johannesen8830f922009-05-19 00:46:42 +00001152 Out << ')';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001153 }
1154 return;
1155 }
1156
1157 switch (CPV->getType()->getTypeID()) {
1158 case Type::FloatTyID:
Dale Johannesen137cef62007-09-17 00:38:27 +00001159 case Type::DoubleTyID:
1160 case Type::X86_FP80TyID:
1161 case Type::PPC_FP128TyID:
1162 case Type::FP128TyID: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163 ConstantFP *FPC = cast<ConstantFP>(CPV);
1164 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
1165 if (I != FPConstantMap.end()) {
1166 // Because of FP precision problems we must load from a stack allocated
1167 // value that holds the value in hex.
Dale Johannesen137cef62007-09-17 00:38:27 +00001168 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" :
1169 FPC->getType() == Type::DoubleTy ? "double" :
1170 "long double")
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171 << "*)&FPConstant" << I->second << ')';
1172 } else {
Chris Lattnera68e3512008-10-17 06:11:48 +00001173 double V;
1174 if (FPC->getType() == Type::FloatTy)
1175 V = FPC->getValueAPF().convertToFloat();
1176 else if (FPC->getType() == Type::DoubleTy)
1177 V = FPC->getValueAPF().convertToDouble();
1178 else {
1179 // Long double. Convert the number to double, discarding precision.
1180 // This is not awesome, but it at least makes the CBE output somewhat
1181 // useful.
1182 APFloat Tmp = FPC->getValueAPF();
1183 bool LosesInfo;
1184 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1185 V = Tmp.convertToDouble();
1186 }
1187
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001188 if (IsNAN(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001189 // The value is NaN
1190
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001191 // FIXME the actual NaN bits should be emitted.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001192 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1193 // it's 0x7ff4.
1194 const unsigned long QuietNaN = 0x7ff8UL;
1195 //const unsigned long SignalNaN = 0x7ff4UL;
1196
1197 // We need to grab the first part of the FP #
1198 char Buffer[100];
1199
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001200 uint64_t ll = DoubleToBits(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
1202
1203 std::string Num(&Buffer[0], &Buffer[6]);
1204 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1205
1206 if (FPC->getType() == Type::FloatTy)
1207 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1208 << Buffer << "\") /*nan*/ ";
1209 else
1210 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1211 << Buffer << "\") /*nan*/ ";
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001212 } else if (IsInf(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001213 // The value is Inf
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001214 if (V < 0) Out << '-';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001215 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
1216 << " /*inf*/ ";
1217 } else {
1218 std::string Num;
1219#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1220 // Print out the constant as a floating point number.
1221 char Buffer[100];
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001222 sprintf(Buffer, "%a", V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001223 Num = Buffer;
1224#else
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001225 Num = ftostr(FPC->getValueAPF());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001226#endif
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001227 Out << Num;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001228 }
1229 }
1230 break;
1231 }
1232
1233 case Type::ArrayTyID:
Dan Gohman29b19472008-07-23 18:41:03 +00001234 // Use C99 compound expression literal initializer syntax.
Dan Gohmanad831302008-07-24 17:57:48 +00001235 if (!Static) {
1236 Out << "(";
1237 printType(Out, CPV->getType());
1238 Out << ")";
1239 }
Dan Gohman5d995b02008-06-02 21:30:49 +00001240 Out << "{ "; // Arrays are wrapped in struct types.
Chris Lattner8673e322008-03-02 05:46:57 +00001241 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
Dan Gohmanad831302008-07-24 17:57:48 +00001242 printConstantArray(CA, Static);
Chris Lattner63fb1f02008-03-02 03:16:38 +00001243 } else {
1244 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245 const ArrayType *AT = cast<ArrayType>(CPV->getType());
1246 Out << '{';
1247 if (AT->getNumElements()) {
1248 Out << ' ';
Owen Anderson15b39322009-07-13 04:09:18 +00001249 Constant *CZ = Context->getNullValue(AT->getElementType());
Dan Gohmanad831302008-07-24 17:57:48 +00001250 printConstant(CZ, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1252 Out << ", ";
Dan Gohmanad831302008-07-24 17:57:48 +00001253 printConstant(CZ, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254 }
1255 }
1256 Out << " }";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 }
Dan Gohman5d995b02008-06-02 21:30:49 +00001258 Out << " }"; // Arrays are wrapped in struct types.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259 break;
1260
1261 case Type::VectorTyID:
Chris Lattner70f0f672008-03-02 03:29:50 +00001262 // Use C99 compound expression literal initializer syntax.
Dan Gohmanad831302008-07-24 17:57:48 +00001263 if (!Static) {
1264 Out << "(";
1265 printType(Out, CPV->getType());
1266 Out << ")";
1267 }
Chris Lattner8673e322008-03-02 05:46:57 +00001268 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
Dan Gohmanad831302008-07-24 17:57:48 +00001269 printConstantVector(CV, Static);
Chris Lattner63fb1f02008-03-02 03:16:38 +00001270 } else {
1271 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1272 const VectorType *VT = cast<VectorType>(CPV->getType());
1273 Out << "{ ";
Owen Anderson15b39322009-07-13 04:09:18 +00001274 Constant *CZ = Context->getNullValue(VT->getElementType());
Dan Gohmanad831302008-07-24 17:57:48 +00001275 printConstant(CZ, Static);
Chris Lattner6d4cd9b2008-03-02 03:18:46 +00001276 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
Chris Lattner63fb1f02008-03-02 03:16:38 +00001277 Out << ", ";
Dan Gohmanad831302008-07-24 17:57:48 +00001278 printConstant(CZ, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001279 }
1280 Out << " }";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001281 }
1282 break;
1283
1284 case Type::StructTyID:
Dan Gohman29b19472008-07-23 18:41:03 +00001285 // Use C99 compound expression literal initializer syntax.
Dan Gohmanad831302008-07-24 17:57:48 +00001286 if (!Static) {
1287 Out << "(";
1288 printType(Out, CPV->getType());
1289 Out << ")";
1290 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001291 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1292 const StructType *ST = cast<StructType>(CPV->getType());
1293 Out << '{';
1294 if (ST->getNumElements()) {
1295 Out << ' ';
Owen Anderson15b39322009-07-13 04:09:18 +00001296 printConstant(Context->getNullValue(ST->getElementType(0)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1298 Out << ", ";
Owen Anderson15b39322009-07-13 04:09:18 +00001299 printConstant(Context->getNullValue(ST->getElementType(i)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001300 }
1301 }
1302 Out << " }";
1303 } else {
1304 Out << '{';
1305 if (CPV->getNumOperands()) {
1306 Out << ' ';
Dan Gohmanad831302008-07-24 17:57:48 +00001307 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001308 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1309 Out << ", ";
Dan Gohmanad831302008-07-24 17:57:48 +00001310 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001311 }
1312 }
1313 Out << " }";
1314 }
1315 break;
1316
1317 case Type::PointerTyID:
1318 if (isa<ConstantPointerNull>(CPV)) {
1319 Out << "((";
1320 printType(Out, CPV->getType()); // sign doesn't matter
1321 Out << ")/*NULL*/0)";
1322 break;
1323 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
Dan Gohmanad831302008-07-24 17:57:48 +00001324 writeOperand(GV, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325 break;
1326 }
1327 // FALL THROUGH
1328 default:
Edwin Török4d9756a2009-07-08 20:53:28 +00001329#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 cerr << "Unknown constant type: " << *CPV << "\n";
Edwin Török4d9756a2009-07-08 20:53:28 +00001331#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001332 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333 }
1334}
1335
1336// Some constant expressions need to be casted back to the original types
1337// because their operands were casted to the expected type. This function takes
1338// care of detecting that case and printing the cast for the ConstantExpr.
Dan Gohmanad831302008-07-24 17:57:48 +00001339bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340 bool NeedsExplicitCast = false;
1341 const Type *Ty = CE->getOperand(0)->getType();
1342 bool TypeIsSigned = false;
1343 switch (CE->getOpcode()) {
Dan Gohmane1790de2008-07-18 18:43:12 +00001344 case Instruction::Add:
1345 case Instruction::Sub:
1346 case Instruction::Mul:
1347 // We need to cast integer arithmetic so that it is always performed
1348 // as unsigned, to avoid undefined behavior on overflow.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349 case Instruction::LShr:
1350 case Instruction::URem:
1351 case Instruction::UDiv: NeedsExplicitCast = true; break;
1352 case Instruction::AShr:
1353 case Instruction::SRem:
1354 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1355 case Instruction::SExt:
1356 Ty = CE->getType();
1357 NeedsExplicitCast = true;
1358 TypeIsSigned = true;
1359 break;
1360 case Instruction::ZExt:
1361 case Instruction::Trunc:
1362 case Instruction::FPTrunc:
1363 case Instruction::FPExt:
1364 case Instruction::UIToFP:
1365 case Instruction::SIToFP:
1366 case Instruction::FPToUI:
1367 case Instruction::FPToSI:
1368 case Instruction::PtrToInt:
1369 case Instruction::IntToPtr:
1370 case Instruction::BitCast:
1371 Ty = CE->getType();
1372 NeedsExplicitCast = true;
1373 break;
1374 default: break;
1375 }
1376 if (NeedsExplicitCast) {
1377 Out << "((";
1378 if (Ty->isInteger() && Ty != Type::Int1Ty)
1379 printSimpleType(Out, Ty, TypeIsSigned);
1380 else
1381 printType(Out, Ty); // not integer, sign doesn't matter
1382 Out << ")(";
1383 }
1384 return NeedsExplicitCast;
1385}
1386
1387// Print a constant assuming that it is the operand for a given Opcode. The
1388// opcodes that care about sign need to cast their operands to the expected
1389// type before the operation proceeds. This function does the casting.
1390void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1391
1392 // Extract the operand's type, we'll need it.
1393 const Type* OpTy = CPV->getType();
1394
1395 // Indicate whether to do the cast or not.
1396 bool shouldCast = false;
1397 bool typeIsSigned = false;
1398
1399 // Based on the Opcode for which this Constant is being written, determine
1400 // the new type to which the operand should be casted by setting the value
1401 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1402 // casted below.
1403 switch (Opcode) {
1404 default:
1405 // for most instructions, it doesn't matter
1406 break;
Dan Gohmane1790de2008-07-18 18:43:12 +00001407 case Instruction::Add:
1408 case Instruction::Sub:
1409 case Instruction::Mul:
1410 // We need to cast integer arithmetic so that it is always performed
1411 // as unsigned, to avoid undefined behavior on overflow.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001412 case Instruction::LShr:
1413 case Instruction::UDiv:
1414 case Instruction::URem:
1415 shouldCast = true;
1416 break;
1417 case Instruction::AShr:
1418 case Instruction::SDiv:
1419 case Instruction::SRem:
1420 shouldCast = true;
1421 typeIsSigned = true;
1422 break;
1423 }
1424
1425 // Write out the casted constant if we should, otherwise just write the
1426 // operand.
1427 if (shouldCast) {
1428 Out << "((";
1429 printSimpleType(Out, OpTy, typeIsSigned);
1430 Out << ")";
Dan Gohmanad831302008-07-24 17:57:48 +00001431 printConstant(CPV, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001432 Out << ")";
1433 } else
Dan Gohmanad831302008-07-24 17:57:48 +00001434 printConstant(CPV, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001435}
1436
1437std::string CWriter::GetValueName(const Value *Operand) {
Chris Lattnerb66867f2009-07-13 23:46:46 +00001438 // Mangle globals with the standard mangler interface for LLC compatibility.
1439 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand))
Chris Lattnerb3cdde62009-07-14 18:17:16 +00001440 return Mang->getMangledName(GV);
Chris Lattnerb66867f2009-07-13 23:46:46 +00001441
1442 std::string Name = Operand->getName();
1443
1444 if (Name.empty()) { // Assign unique names to local temporaries.
1445 unsigned &No = AnonValueNumbers[Operand];
1446 if (No == 0)
1447 No = ++NextAnonValueNumber;
1448 Name = "tmp__" + utostr(No);
1449 }
1450
1451 std::string VarName;
1452 VarName.reserve(Name.capacity());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001453
Chris Lattnerb66867f2009-07-13 23:46:46 +00001454 for (std::string::iterator I = Name.begin(), E = Name.end();
1455 I != E; ++I) {
1456 char ch = *I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001457
Chris Lattnerb66867f2009-07-13 23:46:46 +00001458 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1459 (ch >= '0' && ch <= '9') || ch == '_')) {
1460 char buffer[5];
1461 sprintf(buffer, "_%x_", ch);
1462 VarName += buffer;
1463 } else
1464 VarName += ch;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001465 }
1466
Chris Lattnerb66867f2009-07-13 23:46:46 +00001467 return "llvm_cbe_" + VarName;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001468}
1469
Chris Lattnerd70f5a82008-05-31 09:23:55 +00001470/// writeInstComputationInline - Emit the computation for the specified
1471/// instruction inline, with no destination provided.
1472void CWriter::writeInstComputationInline(Instruction &I) {
Dale Johannesen787881e2009-06-18 01:07:23 +00001473 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1474 // Validate this.
1475 const Type *Ty = I.getType();
1476 if (Ty->isInteger() && (Ty!=Type::Int1Ty && Ty!=Type::Int8Ty &&
1477 Ty!=Type::Int16Ty && Ty!=Type::Int32Ty && Ty!=Type::Int64Ty)) {
Edwin Török4d9756a2009-07-08 20:53:28 +00001478 llvm_report_error("The C backend does not currently support integer "
1479 "types of widths other than 1, 8, 16, 32, 64.\n"
1480 "This is being tracked as PR 4158.");
Dale Johannesen787881e2009-06-18 01:07:23 +00001481 }
1482
Chris Lattnerd70f5a82008-05-31 09:23:55 +00001483 // If this is a non-trivial bool computation, make sure to truncate down to
1484 // a 1 bit value. This is important because we want "add i1 x, y" to return
1485 // "0" when x and y are true, not "2" for example.
1486 bool NeedBoolTrunc = false;
1487 if (I.getType() == Type::Int1Ty && !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
1488 NeedBoolTrunc = true;
1489
1490 if (NeedBoolTrunc)
1491 Out << "((";
1492
1493 visit(I);
1494
1495 if (NeedBoolTrunc)
1496 Out << ")&1)";
1497}
1498
1499
Dan Gohmanad831302008-07-24 17:57:48 +00001500void CWriter::writeOperandInternal(Value *Operand, bool Static) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001501 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnerd70f5a82008-05-31 09:23:55 +00001502 // Should we inline this instruction to build a tree?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001503 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001504 Out << '(';
Chris Lattnerd70f5a82008-05-31 09:23:55 +00001505 writeInstComputationInline(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001506 Out << ')';
1507 return;
1508 }
1509
1510 Constant* CPV = dyn_cast<Constant>(Operand);
1511
1512 if (CPV && !isa<GlobalValue>(CPV))
Dan Gohmanad831302008-07-24 17:57:48 +00001513 printConstant(CPV, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001514 else
1515 Out << GetValueName(Operand);
1516}
1517
Dan Gohmanad831302008-07-24 17:57:48 +00001518void CWriter::writeOperand(Value *Operand, bool Static) {
Chris Lattner8bbc8592008-03-02 08:07:24 +00001519 bool isAddressImplicit = isAddressExposed(Operand);
1520 if (isAddressImplicit)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521 Out << "(&"; // Global variables are referenced as their addresses by llvm
1522
Dan Gohmanad831302008-07-24 17:57:48 +00001523 writeOperandInternal(Operand, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001524
Chris Lattner8bbc8592008-03-02 08:07:24 +00001525 if (isAddressImplicit)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001526 Out << ')';
1527}
1528
1529// Some instructions need to have their result value casted back to the
1530// original types because their operands were casted to the expected type.
1531// This function takes care of detecting that case and printing the cast
1532// for the Instruction.
1533bool CWriter::writeInstructionCast(const Instruction &I) {
1534 const Type *Ty = I.getOperand(0)->getType();
1535 switch (I.getOpcode()) {
Dan Gohmane1790de2008-07-18 18:43:12 +00001536 case Instruction::Add:
1537 case Instruction::Sub:
1538 case Instruction::Mul:
1539 // We need to cast integer arithmetic so that it is always performed
1540 // as unsigned, to avoid undefined behavior on overflow.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001541 case Instruction::LShr:
1542 case Instruction::URem:
1543 case Instruction::UDiv:
1544 Out << "((";
1545 printSimpleType(Out, Ty, false);
1546 Out << ")(";
1547 return true;
1548 case Instruction::AShr:
1549 case Instruction::SRem:
1550 case Instruction::SDiv:
1551 Out << "((";
1552 printSimpleType(Out, Ty, true);
1553 Out << ")(";
1554 return true;
1555 default: break;
1556 }
1557 return false;
1558}
1559
1560// Write the operand with a cast to another type based on the Opcode being used.
1561// This will be used in cases where an instruction has specific type
1562// requirements (usually signedness) for its operands.
1563void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1564
1565 // Extract the operand's type, we'll need it.
1566 const Type* OpTy = Operand->getType();
1567
1568 // Indicate whether to do the cast or not.
1569 bool shouldCast = false;
1570
1571 // Indicate whether the cast should be to a signed type or not.
1572 bool castIsSigned = false;
1573
1574 // Based on the Opcode for which this Operand is being written, determine
1575 // the new type to which the operand should be casted by setting the value
1576 // of OpTy. If we change OpTy, also set shouldCast to true.
1577 switch (Opcode) {
1578 default:
1579 // for most instructions, it doesn't matter
1580 break;
Dan Gohmane1790de2008-07-18 18:43:12 +00001581 case Instruction::Add:
1582 case Instruction::Sub:
1583 case Instruction::Mul:
1584 // We need to cast integer arithmetic so that it is always performed
1585 // as unsigned, to avoid undefined behavior on overflow.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001586 case Instruction::LShr:
1587 case Instruction::UDiv:
1588 case Instruction::URem: // Cast to unsigned first
1589 shouldCast = true;
1590 castIsSigned = false;
1591 break;
Chris Lattner7ce1ee42007-09-22 20:16:48 +00001592 case Instruction::GetElementPtr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001593 case Instruction::AShr:
1594 case Instruction::SDiv:
1595 case Instruction::SRem: // Cast to signed first
1596 shouldCast = true;
1597 castIsSigned = true;
1598 break;
1599 }
1600
1601 // Write out the casted operand if we should, otherwise just write the
1602 // operand.
1603 if (shouldCast) {
1604 Out << "((";
1605 printSimpleType(Out, OpTy, castIsSigned);
1606 Out << ")";
1607 writeOperand(Operand);
1608 Out << ")";
1609 } else
1610 writeOperand(Operand);
1611}
1612
1613// Write the operand with a cast to another type based on the icmp predicate
1614// being used.
Chris Lattner389c9142007-09-15 06:51:03 +00001615void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1616 // This has to do a cast to ensure the operand has the right signedness.
1617 // Also, if the operand is a pointer, we make sure to cast to an integer when
1618 // doing the comparison both for signedness and so that the C compiler doesn't
1619 // optimize things like "p < NULL" to false (p may contain an integer value
1620 // f.e.).
1621 bool shouldCast = Cmp.isRelational();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001622
1623 // Write out the casted operand if we should, otherwise just write the
1624 // operand.
Chris Lattner389c9142007-09-15 06:51:03 +00001625 if (!shouldCast) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001626 writeOperand(Operand);
Chris Lattner389c9142007-09-15 06:51:03 +00001627 return;
1628 }
1629
1630 // Should this be a signed comparison? If so, convert to signed.
1631 bool castIsSigned = Cmp.isSignedPredicate();
1632
1633 // If the operand was a pointer, convert to a large integer type.
1634 const Type* OpTy = Operand->getType();
1635 if (isa<PointerType>(OpTy))
1636 OpTy = TD->getIntPtrType();
1637
1638 Out << "((";
1639 printSimpleType(Out, OpTy, castIsSigned);
1640 Out << ")";
1641 writeOperand(Operand);
1642 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001643}
1644
1645// generateCompilerSpecificCode - This is where we add conditional compilation
1646// directives to cater to specific compilers as need be.
1647//
David Greene302008d2009-07-14 20:18:05 +00001648static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
Dan Gohman3f795232008-04-02 23:52:49 +00001649 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001650 // Alloca is hard to get, and we don't want to include stdlib.h here.
1651 Out << "/* get a declaration for alloca */\n"
1652 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1653 << "#define alloca(x) __builtin_alloca((x))\n"
1654 << "#define _alloca(x) __builtin_alloca((x))\n"
1655 << "#elif defined(__APPLE__)\n"
1656 << "extern void *__builtin_alloca(unsigned long);\n"
1657 << "#define alloca(x) __builtin_alloca(x)\n"
1658 << "#define longjmp _longjmp\n"
1659 << "#define setjmp _setjmp\n"
1660 << "#elif defined(__sun__)\n"
1661 << "#if defined(__sparcv9)\n"
1662 << "extern void *__builtin_alloca(unsigned long);\n"
1663 << "#else\n"
1664 << "extern void *__builtin_alloca(unsigned int);\n"
1665 << "#endif\n"
1666 << "#define alloca(x) __builtin_alloca(x)\n"
Matthijs Kooijman331217d2008-06-26 10:36:58 +00001667 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001668 << "#define alloca(x) __builtin_alloca(x)\n"
1669 << "#elif defined(_MSC_VER)\n"
1670 << "#define inline _inline\n"
1671 << "#define alloca(x) _alloca(x)\n"
1672 << "#else\n"
1673 << "#include <alloca.h>\n"
1674 << "#endif\n\n";
1675
1676 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1677 // If we aren't being compiled with GCC, just drop these attributes.
1678 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1679 << "#define __attribute__(X)\n"
1680 << "#endif\n\n";
1681
1682 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1683 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1684 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1685 << "#elif defined(__GNUC__)\n"
1686 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1687 << "#else\n"
1688 << "#define __EXTERNAL_WEAK__\n"
1689 << "#endif\n\n";
1690
1691 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1692 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1693 << "#define __ATTRIBUTE_WEAK__\n"
1694 << "#elif defined(__GNUC__)\n"
1695 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1696 << "#else\n"
1697 << "#define __ATTRIBUTE_WEAK__\n"
1698 << "#endif\n\n";
1699
1700 // Add hidden visibility support. FIXME: APPLE_CC?
1701 Out << "#if defined(__GNUC__)\n"
1702 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1703 << "#endif\n\n";
1704
1705 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1706 // From the GCC documentation:
1707 //
1708 // double __builtin_nan (const char *str)
1709 //
1710 // This is an implementation of the ISO C99 function nan.
1711 //
1712 // Since ISO C99 defines this function in terms of strtod, which we do
1713 // not implement, a description of the parsing is in order. The string is
1714 // parsed as by strtol; that is, the base is recognized by leading 0 or
1715 // 0x prefixes. The number parsed is placed in the significand such that
1716 // the least significant bit of the number is at the least significant
1717 // bit of the significand. The number is truncated to fit the significand
1718 // field provided. The significand is forced to be a quiet NaN.
1719 //
1720 // This function, if given a string literal, is evaluated early enough
1721 // that it is considered a compile-time constant.
1722 //
1723 // float __builtin_nanf (const char *str)
1724 //
1725 // Similar to __builtin_nan, except the return type is float.
1726 //
1727 // double __builtin_inf (void)
1728 //
1729 // Similar to __builtin_huge_val, except a warning is generated if the
1730 // target floating-point format does not support infinities. This
1731 // function is suitable for implementing the ISO C99 macro INFINITY.
1732 //
1733 // float __builtin_inff (void)
1734 //
1735 // Similar to __builtin_inf, except the return type is float.
1736 Out << "#ifdef __GNUC__\n"
1737 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1738 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1739 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1740 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1741 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1742 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1743 << "#define LLVM_PREFETCH(addr,rw,locality) "
1744 "__builtin_prefetch(addr,rw,locality)\n"
1745 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1746 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1747 << "#define LLVM_ASM __asm__\n"
1748 << "#else\n"
1749 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1750 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1751 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1752 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1753 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1754 << "#define LLVM_INFF 0.0F /* Float */\n"
1755 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1756 << "#define __ATTRIBUTE_CTOR__\n"
1757 << "#define __ATTRIBUTE_DTOR__\n"
1758 << "#define LLVM_ASM(X)\n"
1759 << "#endif\n\n";
1760
1761 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1762 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1763 << "#define __builtin_stack_restore(X) /* noop */\n"
1764 << "#endif\n\n";
1765
Dan Gohman3f795232008-04-02 23:52:49 +00001766 // Output typedefs for 128-bit integers. If these are needed with a
1767 // 32-bit target or with a C compiler that doesn't support mode(TI),
1768 // more drastic measures will be needed.
Chris Lattnerab6d3382008-06-16 04:25:29 +00001769 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1770 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1771 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1772 << "#endif\n\n";
Dan Gohmana2245af2008-04-02 19:40:14 +00001773
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001774 // Output target-specific code that should be inserted into main.
1775 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001776}
1777
1778/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1779/// the StaticTors set.
1780static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1781 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1782 if (!InitList) return;
1783
1784 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1785 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1786 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1787
1788 if (CS->getOperand(1)->isNullValue())
1789 return; // Found a null terminator, exit printing.
1790 Constant *FP = CS->getOperand(1);
1791 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1792 if (CE->isCast())
1793 FP = CE->getOperand(0);
1794 if (Function *F = dyn_cast<Function>(FP))
1795 StaticTors.insert(F);
1796 }
1797}
1798
1799enum SpecialGlobalClass {
1800 NotSpecial = 0,
1801 GlobalCtors, GlobalDtors,
1802 NotPrinted
1803};
1804
1805/// getGlobalVariableClass - If this is a global that is specially recognized
1806/// by LLVM, return a code that indicates how we should handle it.
1807static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1808 // If this is a global ctors/dtors list, handle it now.
1809 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1810 if (GV->getName() == "llvm.global_ctors")
1811 return GlobalCtors;
1812 else if (GV->getName() == "llvm.global_dtors")
1813 return GlobalDtors;
1814 }
1815
1816 // Otherwise, it it is other metadata, don't print it. This catches things
1817 // like debug information.
1818 if (GV->getSection() == "llvm.metadata")
1819 return NotPrinted;
1820
1821 return NotSpecial;
1822}
1823
1824
1825bool CWriter::doInitialization(Module &M) {
1826 // Initialize
1827 TheModule = &M;
1828
1829 TD = new TargetData(&M);
1830 IL = new IntrinsicLowering(*TD);
1831 IL->AddPrototypes(M);
1832
1833 // Ensure that all structure types have names...
1834 Mang = new Mangler(M);
1835 Mang->markCharUnacceptable('.');
1836
1837 // Keep track of which functions are static ctors/dtors so they can have
1838 // an attribute added to their prototypes.
1839 std::set<Function*> StaticCtors, StaticDtors;
1840 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1841 I != E; ++I) {
1842 switch (getGlobalVariableClass(I)) {
1843 default: break;
1844 case GlobalCtors:
1845 FindStaticTors(I, StaticCtors);
1846 break;
1847 case GlobalDtors:
1848 FindStaticTors(I, StaticDtors);
1849 break;
1850 }
1851 }
1852
1853 // get declaration for alloca
1854 Out << "/* Provide Declarations */\n";
1855 Out << "#include <stdarg.h>\n"; // Varargs support
1856 Out << "#include <setjmp.h>\n"; // Unwind support
Dan Gohman3f795232008-04-02 23:52:49 +00001857 generateCompilerSpecificCode(Out, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001858
1859 // Provide a definition for `bool' if not compiling with a C++ compiler.
1860 Out << "\n"
1861 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1862
1863 << "\n\n/* Support for floating point constants */\n"
1864 << "typedef unsigned long long ConstantDoubleTy;\n"
1865 << "typedef unsigned int ConstantFloatTy;\n"
Dale Johannesen137cef62007-09-17 00:38:27 +00001866 << "typedef struct { unsigned long long f1; unsigned short f2; "
1867 "unsigned short pad[3]; } ConstantFP80Ty;\n"
Dale Johannesen091dcfd2007-10-15 01:05:37 +00001868 // This is used for both kinds of 128-bit long double; meaning differs.
Dale Johannesen137cef62007-09-17 00:38:27 +00001869 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1870 " ConstantFP128Ty;\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001871 << "\n\n/* Global Declarations */\n";
1872
1873 // First output all the declarations for the program, because C requires
1874 // Functions & globals to be declared before they are used.
1875 //
1876
1877 // Loop over the symbol table, emitting all named constants...
1878 printModuleTypes(M.getTypeSymbolTable());
1879
1880 // Global variable declarations...
1881 if (!M.global_empty()) {
1882 Out << "\n/* External Global Variable Declarations */\n";
1883 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1884 I != E; ++I) {
1885
Dale Johannesen49c44122008-05-14 20:12:51 +00001886 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1887 I->hasCommonLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001888 Out << "extern ";
1889 else if (I->hasDLLImportLinkage())
1890 Out << "__declspec(dllimport) ";
1891 else
1892 continue; // Internal Global
1893
1894 // Thread Local Storage
1895 if (I->isThreadLocal())
1896 Out << "__thread ";
1897
1898 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1899
1900 if (I->hasExternalWeakLinkage())
1901 Out << " __EXTERNAL_WEAK__";
1902 Out << ";\n";
1903 }
1904 }
1905
1906 // Function declarations
1907 Out << "\n/* Function Declarations */\n";
1908 Out << "double fmod(double, double);\n"; // Support for FP rem
1909 Out << "float fmodf(float, float);\n";
Dale Johannesen137cef62007-09-17 00:38:27 +00001910 Out << "long double fmodl(long double, long double);\n";
Evan Chengd2d22fe2008-06-07 07:50:29 +00001911
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001912 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1913 // Don't print declarations for intrinsic functions.
Duncan Sands79d28872007-12-03 20:06:50 +00001914 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001915 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1916 if (I->hasExternalWeakLinkage())
1917 Out << "extern ";
1918 printFunctionSignature(I, true);
Evan Chengd2d22fe2008-06-07 07:50:29 +00001919 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001920 Out << " __ATTRIBUTE_WEAK__";
1921 if (I->hasExternalWeakLinkage())
1922 Out << " __EXTERNAL_WEAK__";
1923 if (StaticCtors.count(I))
1924 Out << " __ATTRIBUTE_CTOR__";
1925 if (StaticDtors.count(I))
1926 Out << " __ATTRIBUTE_DTOR__";
1927 if (I->hasHiddenVisibility())
1928 Out << " __HIDDEN__";
Evan Chengd2d22fe2008-06-07 07:50:29 +00001929
1930 if (I->hasName() && I->getName()[0] == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001931 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
Evan Chengd2d22fe2008-06-07 07:50:29 +00001932
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001933 Out << ";\n";
1934 }
1935 }
1936
1937 // Output the global variable declarations
1938 if (!M.global_empty()) {
1939 Out << "\n\n/* Global Variable Declarations */\n";
1940 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1941 I != E; ++I)
1942 if (!I->isDeclaration()) {
1943 // Ignore special globals, such as debug info.
1944 if (getGlobalVariableClass(I))
1945 continue;
1946
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001947 if (I->hasLocalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001948 Out << "static ";
1949 else
1950 Out << "extern ";
1951
1952 // Thread Local Storage
1953 if (I->isThreadLocal())
1954 Out << "__thread ";
1955
1956 printType(Out, I->getType()->getElementType(), false,
1957 GetValueName(I));
1958
1959 if (I->hasLinkOnceLinkage())
1960 Out << " __attribute__((common))";
Dale Johannesen49c44122008-05-14 20:12:51 +00001961 else if (I->hasCommonLinkage()) // FIXME is this right?
1962 Out << " __ATTRIBUTE_WEAK__";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001963 else if (I->hasWeakLinkage())
1964 Out << " __ATTRIBUTE_WEAK__";
1965 else if (I->hasExternalWeakLinkage())
1966 Out << " __EXTERNAL_WEAK__";
1967 if (I->hasHiddenVisibility())
1968 Out << " __HIDDEN__";
1969 Out << ";\n";
1970 }
1971 }
1972
1973 // Output the global variable definitions and contents...
1974 if (!M.global_empty()) {
1975 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Evan Chengd2d22fe2008-06-07 07:50:29 +00001976 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001977 I != E; ++I)
1978 if (!I->isDeclaration()) {
1979 // Ignore special globals, such as debug info.
1980 if (getGlobalVariableClass(I))
1981 continue;
1982
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001983 if (I->hasLocalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001984 Out << "static ";
1985 else if (I->hasDLLImportLinkage())
1986 Out << "__declspec(dllimport) ";
1987 else if (I->hasDLLExportLinkage())
1988 Out << "__declspec(dllexport) ";
1989
1990 // Thread Local Storage
1991 if (I->isThreadLocal())
1992 Out << "__thread ";
1993
1994 printType(Out, I->getType()->getElementType(), false,
1995 GetValueName(I));
1996 if (I->hasLinkOnceLinkage())
1997 Out << " __attribute__((common))";
1998 else if (I->hasWeakLinkage())
1999 Out << " __ATTRIBUTE_WEAK__";
Dale Johannesen49c44122008-05-14 20:12:51 +00002000 else if (I->hasCommonLinkage())
2001 Out << " __ATTRIBUTE_WEAK__";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002002
2003 if (I->hasHiddenVisibility())
2004 Out << " __HIDDEN__";
2005
2006 // If the initializer is not null, emit the initializer. If it is null,
2007 // we try to avoid emitting large amounts of zeros. The problem with
2008 // this, however, occurs when the variable has weak linkage. In this
2009 // case, the assembler will complain about the variable being both weak
2010 // and common, so we disable this optimization.
Dale Johannesen49c44122008-05-14 20:12:51 +00002011 // FIXME common linkage should avoid this problem.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002012 if (!I->getInitializer()->isNullValue()) {
2013 Out << " = " ;
Dan Gohmanad831302008-07-24 17:57:48 +00002014 writeOperand(I->getInitializer(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002015 } else if (I->hasWeakLinkage()) {
2016 // We have to specify an initializer, but it doesn't have to be
2017 // complete. If the value is an aggregate, print out { 0 }, and let
2018 // the compiler figure out the rest of the zeros.
2019 Out << " = " ;
2020 if (isa<StructType>(I->getInitializer()->getType()) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002021 isa<VectorType>(I->getInitializer()->getType())) {
2022 Out << "{ 0 }";
Dan Gohman5d995b02008-06-02 21:30:49 +00002023 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
2024 // As with structs and vectors, but with an extra set of braces
2025 // because arrays are wrapped in structs.
2026 Out << "{ { 0 } }";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002027 } else {
2028 // Just print it out normally.
Dan Gohmanad831302008-07-24 17:57:48 +00002029 writeOperand(I->getInitializer(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002030 }
2031 }
2032 Out << ";\n";
2033 }
2034 }
2035
2036 if (!M.empty())
2037 Out << "\n\n/* Function Bodies */\n";
2038
2039 // Emit some helper functions for dealing with FCMP instruction's
2040 // predicates
2041 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2042 Out << "return X == X && Y == Y; }\n";
2043 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2044 Out << "return X != X || Y != Y; }\n";
2045 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
2046 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
2047 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
2048 Out << "return X != Y; }\n";
2049 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
2050 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
2051 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
2052 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
2053 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
2054 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
2055 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
2056 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
2057 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
2058 Out << "return X == Y ; }\n";
2059 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
2060 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
2061 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
2062 Out << "return X < Y ; }\n";
2063 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
2064 Out << "return X > Y ; }\n";
2065 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
2066 Out << "return X <= Y ; }\n";
2067 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
2068 Out << "return X >= Y ; }\n";
2069 return false;
2070}
2071
2072
2073/// Output all floating point constants that cannot be printed accurately...
2074void CWriter::printFloatingPointConstants(Function &F) {
2075 // Scan the module for floating point constants. If any FP constant is used
2076 // in the function, we want to redirect it here so that we do not depend on
2077 // the precision of the printed form, unless the printed form preserves
2078 // precision.
2079 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002080 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2081 I != E; ++I)
Chris Lattnerf6e12012008-10-22 04:53:16 +00002082 printFloatingPointConstants(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002083
2084 Out << '\n';
2085}
2086
Chris Lattnerf6e12012008-10-22 04:53:16 +00002087void CWriter::printFloatingPointConstants(const Constant *C) {
2088 // If this is a constant expression, recursively check for constant fp values.
2089 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2090 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2091 printFloatingPointConstants(CE->getOperand(i));
2092 return;
2093 }
2094
2095 // Otherwise, check for a FP constant that we need to print.
2096 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2097 if (FPC == 0 ||
2098 // Do not put in FPConstantMap if safe.
2099 isFPCSafeToPrint(FPC) ||
2100 // Already printed this constant?
2101 FPConstantMap.count(FPC))
2102 return;
2103
2104 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2105
2106 if (FPC->getType() == Type::DoubleTy) {
2107 double Val = FPC->getValueAPF().convertToDouble();
2108 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2109 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2110 << " = 0x" << utohexstr(i)
2111 << "ULL; /* " << Val << " */\n";
2112 } else if (FPC->getType() == Type::FloatTy) {
2113 float Val = FPC->getValueAPF().convertToFloat();
2114 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2115 getZExtValue();
2116 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2117 << " = 0x" << utohexstr(i)
2118 << "U; /* " << Val << " */\n";
2119 } else if (FPC->getType() == Type::X86_FP80Ty) {
2120 // api needed to prevent premature destruction
2121 APInt api = FPC->getValueAPF().bitcastToAPInt();
2122 const uint64_t *p = api.getRawData();
2123 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
Dale Johannesen0a92eac2009-03-23 21:16:53 +00002124 << " = { 0x" << utohexstr(p[0])
2125 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
Chris Lattnerf6e12012008-10-22 04:53:16 +00002126 << "}; /* Long double constant */\n";
2127 } else if (FPC->getType() == Type::PPC_FP128Ty) {
2128 APInt api = FPC->getValueAPF().bitcastToAPInt();
2129 const uint64_t *p = api.getRawData();
2130 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2131 << " = { 0x"
2132 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2133 << "}; /* Long double constant */\n";
2134
2135 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00002136 llvm_unreachable("Unknown float type!");
Chris Lattnerf6e12012008-10-22 04:53:16 +00002137 }
2138}
2139
2140
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002141
2142/// printSymbolTable - Run through symbol table looking for type names. If a
2143/// type name is found, emit its declaration...
2144///
2145void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
2146 Out << "/* Helper union for bitcasts */\n";
2147 Out << "typedef union {\n";
2148 Out << " unsigned int Int32;\n";
2149 Out << " unsigned long long Int64;\n";
2150 Out << " float Float;\n";
2151 Out << " double Double;\n";
2152 Out << "} llvmBitCastUnion;\n";
2153
2154 // We are only interested in the type plane of the symbol table.
2155 TypeSymbolTable::const_iterator I = TST.begin();
2156 TypeSymbolTable::const_iterator End = TST.end();
2157
2158 // If there are no type names, exit early.
2159 if (I == End) return;
2160
2161 // Print out forward declarations for structure types before anything else!
2162 Out << "/* Structure forward decls */\n";
2163 for (; I != End; ++I) {
2164 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
2165 Out << Name << ";\n";
2166 TypeNames.insert(std::make_pair(I->second, Name));
2167 }
2168
2169 Out << '\n';
2170
2171 // Now we can print out typedefs. Above, we guaranteed that this can only be
2172 // for struct or opaque types.
2173 Out << "/* Typedefs */\n";
2174 for (I = TST.begin(); I != End; ++I) {
2175 std::string Name = "l_" + Mang->makeNameProper(I->first);
2176 Out << "typedef ";
2177 printType(Out, I->second, false, Name);
2178 Out << ";\n";
2179 }
2180
2181 Out << '\n';
2182
2183 // Keep track of which structures have been printed so far...
Dan Gohman5d995b02008-06-02 21:30:49 +00002184 std::set<const Type *> StructPrinted;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002185
2186 // Loop over all structures then push them into the stack so they are
2187 // printed in the correct order.
2188 //
2189 Out << "/* Structure contents */\n";
2190 for (I = TST.begin(); I != End; ++I)
Dan Gohman5d995b02008-06-02 21:30:49 +00002191 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002192 // Only print out used types!
Dan Gohman5d995b02008-06-02 21:30:49 +00002193 printContainedStructs(I->second, StructPrinted);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002194}
2195
2196// Push the struct onto the stack and recursively push all structs
2197// this one depends on.
2198//
2199// TODO: Make this work properly with vector types
2200//
2201void CWriter::printContainedStructs(const Type *Ty,
Dan Gohman5d995b02008-06-02 21:30:49 +00002202 std::set<const Type*> &StructPrinted) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002203 // Don't walk through pointers.
2204 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
2205
2206 // Print all contained types first.
2207 for (Type::subtype_iterator I = Ty->subtype_begin(),
2208 E = Ty->subtype_end(); I != E; ++I)
2209 printContainedStructs(*I, StructPrinted);
2210
Dan Gohman5d995b02008-06-02 21:30:49 +00002211 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002212 // Check to see if we have already printed this struct.
Dan Gohman5d995b02008-06-02 21:30:49 +00002213 if (StructPrinted.insert(Ty).second) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002214 // Print structure type out.
Dan Gohman5d995b02008-06-02 21:30:49 +00002215 std::string Name = TypeNames[Ty];
2216 printType(Out, Ty, false, Name, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002217 Out << ";\n\n";
2218 }
2219 }
2220}
2221
2222void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
2223 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel949a4b72008-03-03 21:46:28 +00002224 bool isStructReturn = F->hasStructRetAttr();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002225
Rafael Espindolaa168fc92009-01-15 20:18:42 +00002226 if (F->hasLocalLinkage()) Out << "static ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002227 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2228 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
2229 switch (F->getCallingConv()) {
2230 case CallingConv::X86_StdCall:
Nick Lewyckyc0b01ea2008-11-26 03:17:27 +00002231 Out << "__attribute__((stdcall)) ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002232 break;
2233 case CallingConv::X86_FastCall:
Nick Lewyckyc0b01ea2008-11-26 03:17:27 +00002234 Out << "__attribute__((fastcall)) ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235 break;
2236 }
2237
2238 // Loop over the arguments, printing them...
2239 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Devang Pateld222f862008-09-25 21:00:45 +00002240 const AttrListPtr &PAL = F->getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002241
2242 std::stringstream FunctionInnards;
2243
2244 // Print out the name...
2245 FunctionInnards << GetValueName(F) << '(';
2246
2247 bool PrintedArg = false;
2248 if (!F->isDeclaration()) {
2249 if (!F->arg_empty()) {
2250 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
Evan Cheng2054cb02008-01-11 03:07:46 +00002251 unsigned Idx = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002252
2253 // If this is a struct-return function, don't print the hidden
2254 // struct-return argument.
2255 if (isStructReturn) {
2256 assert(I != E && "Invalid struct return function!");
2257 ++I;
Evan Cheng2054cb02008-01-11 03:07:46 +00002258 ++Idx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002259 }
2260
2261 std::string ArgName;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002262 for (; I != E; ++I) {
2263 if (PrintedArg) FunctionInnards << ", ";
2264 if (I->hasName() || !Prototype)
2265 ArgName = GetValueName(I);
2266 else
2267 ArgName = "";
Evan Cheng2054cb02008-01-11 03:07:46 +00002268 const Type *ArgTy = I->getType();
Devang Pateld222f862008-09-25 21:00:45 +00002269 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng17254e62008-01-11 09:12:49 +00002270 ArgTy = cast<PointerType>(ArgTy)->getElementType();
Chris Lattner8bbc8592008-03-02 08:07:24 +00002271 ByValParams.insert(I);
Evan Cheng17254e62008-01-11 09:12:49 +00002272 }
Evan Cheng2054cb02008-01-11 03:07:46 +00002273 printType(FunctionInnards, ArgTy,
Devang Pateld222f862008-09-25 21:00:45 +00002274 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002275 ArgName);
2276 PrintedArg = true;
2277 ++Idx;
2278 }
2279 }
2280 } else {
2281 // Loop over the arguments, printing them.
2282 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
Evan Chengf8956382008-01-11 23:10:11 +00002283 unsigned Idx = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002284
2285 // If this is a struct-return function, don't print the hidden
2286 // struct-return argument.
2287 if (isStructReturn) {
2288 assert(I != E && "Invalid struct return function!");
2289 ++I;
Evan Chengf8956382008-01-11 23:10:11 +00002290 ++Idx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002291 }
2292
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002293 for (; I != E; ++I) {
2294 if (PrintedArg) FunctionInnards << ", ";
Evan Chengf8956382008-01-11 23:10:11 +00002295 const Type *ArgTy = *I;
Devang Pateld222f862008-09-25 21:00:45 +00002296 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Chengf8956382008-01-11 23:10:11 +00002297 assert(isa<PointerType>(ArgTy));
2298 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2299 }
2300 printType(FunctionInnards, ArgTy,
Devang Pateld222f862008-09-25 21:00:45 +00002301 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002302 PrintedArg = true;
2303 ++Idx;
2304 }
2305 }
2306
2307 // Finish printing arguments... if this is a vararg function, print the ...,
2308 // unless there are no known types, in which case, we just emit ().
2309 //
2310 if (FT->isVarArg() && PrintedArg) {
2311 if (PrintedArg) FunctionInnards << ", ";
2312 FunctionInnards << "..."; // Output varargs portion of signature!
2313 } else if (!FT->isVarArg() && !PrintedArg) {
2314 FunctionInnards << "void"; // ret() -> ret(void) in C.
2315 }
2316 FunctionInnards << ')';
2317
2318 // Get the return tpe for the function.
2319 const Type *RetTy;
2320 if (!isStructReturn)
2321 RetTy = F->getReturnType();
2322 else {
2323 // If this is a struct-return function, print the struct-return type.
2324 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2325 }
2326
2327 // Print out the return type and the signature built above.
2328 printType(Out, RetTy,
Devang Pateld222f862008-09-25 21:00:45 +00002329 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002330 FunctionInnards.str());
2331}
2332
2333static inline bool isFPIntBitCast(const Instruction &I) {
2334 if (!isa<BitCastInst>(I))
2335 return false;
2336 const Type *SrcTy = I.getOperand(0)->getType();
2337 const Type *DstTy = I.getType();
2338 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2339 (DstTy->isFloatingPoint() && SrcTy->isInteger());
2340}
2341
2342void CWriter::printFunction(Function &F) {
2343 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel949a4b72008-03-03 21:46:28 +00002344 bool isStructReturn = F.hasStructRetAttr();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002345
2346 printFunctionSignature(&F, false);
2347 Out << " {\n";
2348
2349 // If this is a struct return function, handle the result with magic.
2350 if (isStructReturn) {
2351 const Type *StructTy =
2352 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2353 Out << " ";
2354 printType(Out, StructTy, false, "StructReturn");
2355 Out << "; /* Struct return temporary */\n";
2356
2357 Out << " ";
2358 printType(Out, F.arg_begin()->getType(), false,
2359 GetValueName(F.arg_begin()));
2360 Out << " = &StructReturn;\n";
2361 }
2362
2363 bool PrintedVar = false;
2364
2365 // print local variable information for the function
2366 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2367 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2368 Out << " ";
2369 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2370 Out << "; /* Address-exposed local */\n";
2371 PrintedVar = true;
2372 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
2373 Out << " ";
2374 printType(Out, I->getType(), false, GetValueName(&*I));
2375 Out << ";\n";
2376
2377 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2378 Out << " ";
2379 printType(Out, I->getType(), false,
2380 GetValueName(&*I)+"__PHI_TEMPORARY");
2381 Out << ";\n";
2382 }
2383 PrintedVar = true;
2384 }
2385 // We need a temporary for the BitCast to use so it can pluck a value out
2386 // of a union to do the BitCast. This is separate from the need for a
2387 // variable to hold the result of the BitCast.
2388 if (isFPIntBitCast(*I)) {
2389 Out << " llvmBitCastUnion " << GetValueName(&*I)
2390 << "__BITCAST_TEMPORARY;\n";
2391 PrintedVar = true;
2392 }
2393 }
2394
2395 if (PrintedVar)
2396 Out << '\n';
2397
2398 if (F.hasExternalLinkage() && F.getName() == "main")
2399 Out << " CODE_FOR_MAIN();\n";
2400
2401 // print the basic blocks
2402 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2403 if (Loop *L = LI->getLoopFor(BB)) {
2404 if (L->getHeader() == BB && L->getParentLoop() == 0)
2405 printLoop(L);
2406 } else {
2407 printBasicBlock(BB);
2408 }
2409 }
2410
2411 Out << "}\n\n";
2412}
2413
2414void CWriter::printLoop(Loop *L) {
2415 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2416 << "' to make GCC happy */\n";
2417 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2418 BasicBlock *BB = L->getBlocks()[i];
2419 Loop *BBLoop = LI->getLoopFor(BB);
2420 if (BBLoop == L)
2421 printBasicBlock(BB);
2422 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2423 printLoop(BBLoop);
2424 }
2425 Out << " } while (1); /* end of syntactic loop '"
2426 << L->getHeader()->getName() << "' */\n";
2427}
2428
2429void CWriter::printBasicBlock(BasicBlock *BB) {
2430
2431 // Don't print the label for the basic block if there are no uses, or if
2432 // the only terminator use is the predecessor basic block's terminator.
2433 // We have to scan the use list because PHI nodes use basic blocks too but
2434 // do not require a label to be generated.
2435 //
2436 bool NeedsLabel = false;
2437 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2438 if (isGotoCodeNecessary(*PI, BB)) {
2439 NeedsLabel = true;
2440 break;
2441 }
2442
2443 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2444
2445 // Output all of the instructions in the basic block...
2446 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2447 ++II) {
2448 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2449 if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
2450 outputLValue(II);
2451 else
2452 Out << " ";
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002453 writeInstComputationInline(*II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002454 Out << ";\n";
2455 }
2456 }
2457
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002458 // Don't emit prefix or suffix for the terminator.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002459 visit(*BB->getTerminator());
2460}
2461
2462
2463// Specific Instruction type classes... note that all of the casts are
2464// necessary because we use the instruction classes as opaque types...
2465//
2466void CWriter::visitReturnInst(ReturnInst &I) {
2467 // If this is a struct return function, return the temporary struct.
Devang Patel949a4b72008-03-03 21:46:28 +00002468 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002469
2470 if (isStructReturn) {
2471 Out << " return StructReturn;\n";
2472 return;
2473 }
2474
2475 // Don't output a void return if this is the last basic block in the function
2476 if (I.getNumOperands() == 0 &&
2477 &*--I.getParent()->getParent()->end() == I.getParent() &&
2478 !I.getParent()->size() == 1) {
2479 return;
2480 }
2481
Dan Gohman93d04582008-04-23 21:49:29 +00002482 if (I.getNumOperands() > 1) {
2483 Out << " {\n";
2484 Out << " ";
2485 printType(Out, I.getParent()->getParent()->getReturnType());
2486 Out << " llvm_cbe_mrv_temp = {\n";
2487 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2488 Out << " ";
2489 writeOperand(I.getOperand(i));
2490 if (i != e - 1)
2491 Out << ",";
2492 Out << "\n";
2493 }
2494 Out << " };\n";
2495 Out << " return llvm_cbe_mrv_temp;\n";
2496 Out << " }\n";
2497 return;
2498 }
2499
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002500 Out << " return";
2501 if (I.getNumOperands()) {
2502 Out << ' ';
2503 writeOperand(I.getOperand(0));
2504 }
2505 Out << ";\n";
2506}
2507
2508void CWriter::visitSwitchInst(SwitchInst &SI) {
2509
2510 Out << " switch (";
2511 writeOperand(SI.getOperand(0));
2512 Out << ") {\n default:\n";
2513 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2514 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2515 Out << ";\n";
2516 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2517 Out << " case ";
2518 writeOperand(SI.getOperand(i));
2519 Out << ":\n";
2520 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2521 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2522 printBranchToBlock(SI.getParent(), Succ, 2);
2523 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
2524 Out << " break;\n";
2525 }
2526 Out << " }\n";
2527}
2528
2529void CWriter::visitUnreachableInst(UnreachableInst &I) {
2530 Out << " /*UNREACHABLE*/;\n";
2531}
2532
2533bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2534 /// FIXME: This should be reenabled, but loop reordering safe!!
2535 return true;
2536
2537 if (next(Function::iterator(From)) != Function::iterator(To))
2538 return true; // Not the direct successor, we need a goto.
2539
2540 //isa<SwitchInst>(From->getTerminator())
2541
2542 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2543 return true;
2544 return false;
2545}
2546
2547void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2548 BasicBlock *Successor,
2549 unsigned Indent) {
2550 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2551 PHINode *PN = cast<PHINode>(I);
2552 // Now we have to do the printing.
2553 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2554 if (!isa<UndefValue>(IV)) {
2555 Out << std::string(Indent, ' ');
2556 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2557 writeOperand(IV);
2558 Out << "; /* for PHI node */\n";
2559 }
2560 }
2561}
2562
2563void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2564 unsigned Indent) {
2565 if (isGotoCodeNecessary(CurBB, Succ)) {
2566 Out << std::string(Indent, ' ') << " goto ";
2567 writeOperand(Succ);
2568 Out << ";\n";
2569 }
2570}
2571
2572// Branch instruction printing - Avoid printing out a branch to a basic block
2573// that immediately succeeds the current one.
2574//
2575void CWriter::visitBranchInst(BranchInst &I) {
2576
2577 if (I.isConditional()) {
2578 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2579 Out << " if (";
2580 writeOperand(I.getCondition());
2581 Out << ") {\n";
2582
2583 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2584 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2585
2586 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2587 Out << " } else {\n";
2588 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2589 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2590 }
2591 } else {
2592 // First goto not necessary, assume second one is...
2593 Out << " if (!";
2594 writeOperand(I.getCondition());
2595 Out << ") {\n";
2596
2597 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2598 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2599 }
2600
2601 Out << " }\n";
2602 } else {
2603 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2604 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2605 }
2606 Out << "\n";
2607}
2608
2609// PHI nodes get copied into temporary values at the end of predecessor basic
2610// blocks. We now need to copy these temporary values into the REAL value for
2611// the PHI.
2612void CWriter::visitPHINode(PHINode &I) {
2613 writeOperand(&I);
2614 Out << "__PHI_TEMPORARY";
2615}
2616
2617
2618void CWriter::visitBinaryOperator(Instruction &I) {
2619 // binary instructions, shift instructions, setCond instructions.
2620 assert(!isa<PointerType>(I.getType()));
2621
2622 // We must cast the results of binary operations which might be promoted.
2623 bool needsCast = false;
2624 if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty)
2625 || (I.getType() == Type::FloatTy)) {
2626 needsCast = true;
2627 Out << "((";
2628 printType(Out, I.getType(), false);
2629 Out << ")(";
2630 }
2631
2632 // If this is a negation operation, print it out as such. For FP, we don't
2633 // want to print "-0.0 - X".
Owen Anderson76f49252009-07-13 22:18:28 +00002634 if (BinaryOperator::isNeg(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002635 Out << "-(";
2636 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2637 Out << ")";
Owen Anderson76f49252009-07-13 22:18:28 +00002638 } else if (BinaryOperator::isFNeg(&I)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002639 Out << "-(";
2640 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2641 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002642 } else if (I.getOpcode() == Instruction::FRem) {
2643 // Output a call to fmod/fmodf instead of emitting a%b
2644 if (I.getType() == Type::FloatTy)
2645 Out << "fmodf(";
Dale Johannesen137cef62007-09-17 00:38:27 +00002646 else if (I.getType() == Type::DoubleTy)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002647 Out << "fmod(";
Dale Johannesen137cef62007-09-17 00:38:27 +00002648 else // all 3 flavors of long double
2649 Out << "fmodl(";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002650 writeOperand(I.getOperand(0));
2651 Out << ", ";
2652 writeOperand(I.getOperand(1));
2653 Out << ")";
2654 } else {
2655
2656 // Write out the cast of the instruction's value back to the proper type
2657 // if necessary.
2658 bool NeedsClosingParens = writeInstructionCast(I);
2659
2660 // Certain instructions require the operand to be forced to a specific type
2661 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2662 // below for operand 1
2663 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2664
2665 switch (I.getOpcode()) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002666 case Instruction::Add:
2667 case Instruction::FAdd: Out << " + "; break;
2668 case Instruction::Sub:
2669 case Instruction::FSub: Out << " - "; break;
2670 case Instruction::Mul:
2671 case Instruction::FMul: Out << " * "; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002672 case Instruction::URem:
2673 case Instruction::SRem:
2674 case Instruction::FRem: Out << " % "; break;
2675 case Instruction::UDiv:
2676 case Instruction::SDiv:
2677 case Instruction::FDiv: Out << " / "; break;
2678 case Instruction::And: Out << " & "; break;
2679 case Instruction::Or: Out << " | "; break;
2680 case Instruction::Xor: Out << " ^ "; break;
2681 case Instruction::Shl : Out << " << "; break;
2682 case Instruction::LShr:
2683 case Instruction::AShr: Out << " >> "; break;
Edwin Török4d9756a2009-07-08 20:53:28 +00002684 default:
2685#ifndef NDEBUG
2686 cerr << "Invalid operator type!" << I;
2687#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00002688 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002689 }
2690
2691 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2692 if (NeedsClosingParens)
2693 Out << "))";
2694 }
2695
2696 if (needsCast) {
2697 Out << "))";
2698 }
2699}
2700
2701void CWriter::visitICmpInst(ICmpInst &I) {
2702 // We must cast the results of icmp which might be promoted.
2703 bool needsCast = false;
2704
2705 // Write out the cast of the instruction's value back to the proper type
2706 // if necessary.
2707 bool NeedsClosingParens = writeInstructionCast(I);
2708
2709 // Certain icmp predicate require the operand to be forced to a specific type
2710 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2711 // below for operand 1
Chris Lattner389c9142007-09-15 06:51:03 +00002712 writeOperandWithCast(I.getOperand(0), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002713
2714 switch (I.getPredicate()) {
2715 case ICmpInst::ICMP_EQ: Out << " == "; break;
2716 case ICmpInst::ICMP_NE: Out << " != "; break;
2717 case ICmpInst::ICMP_ULE:
2718 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2719 case ICmpInst::ICMP_UGE:
2720 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2721 case ICmpInst::ICMP_ULT:
2722 case ICmpInst::ICMP_SLT: Out << " < "; break;
2723 case ICmpInst::ICMP_UGT:
2724 case ICmpInst::ICMP_SGT: Out << " > "; break;
Edwin Török4d9756a2009-07-08 20:53:28 +00002725 default:
2726#ifndef NDEBUG
2727 cerr << "Invalid icmp predicate!" << I;
2728#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00002729 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002730 }
2731
Chris Lattner389c9142007-09-15 06:51:03 +00002732 writeOperandWithCast(I.getOperand(1), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002733 if (NeedsClosingParens)
2734 Out << "))";
2735
2736 if (needsCast) {
2737 Out << "))";
2738 }
2739}
2740
2741void CWriter::visitFCmpInst(FCmpInst &I) {
2742 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2743 Out << "0";
2744 return;
2745 }
2746 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2747 Out << "1";
2748 return;
2749 }
2750
2751 const char* op = 0;
2752 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002753 default: llvm_unreachable("Illegal FCmp predicate");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002754 case FCmpInst::FCMP_ORD: op = "ord"; break;
2755 case FCmpInst::FCMP_UNO: op = "uno"; break;
2756 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2757 case FCmpInst::FCMP_UNE: op = "une"; break;
2758 case FCmpInst::FCMP_ULT: op = "ult"; break;
2759 case FCmpInst::FCMP_ULE: op = "ule"; break;
2760 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2761 case FCmpInst::FCMP_UGE: op = "uge"; break;
2762 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2763 case FCmpInst::FCMP_ONE: op = "one"; break;
2764 case FCmpInst::FCMP_OLT: op = "olt"; break;
2765 case FCmpInst::FCMP_OLE: op = "ole"; break;
2766 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2767 case FCmpInst::FCMP_OGE: op = "oge"; break;
2768 }
2769
2770 Out << "llvm_fcmp_" << op << "(";
2771 // Write the first operand
2772 writeOperand(I.getOperand(0));
2773 Out << ", ";
2774 // Write the second operand
2775 writeOperand(I.getOperand(1));
2776 Out << ")";
2777}
2778
2779static const char * getFloatBitCastField(const Type *Ty) {
2780 switch (Ty->getTypeID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002781 default: llvm_unreachable("Invalid Type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002782 case Type::FloatTyID: return "Float";
2783 case Type::DoubleTyID: return "Double";
2784 case Type::IntegerTyID: {
2785 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2786 if (NumBits <= 32)
2787 return "Int32";
2788 else
2789 return "Int64";
2790 }
2791 }
2792}
2793
2794void CWriter::visitCastInst(CastInst &I) {
2795 const Type *DstTy = I.getType();
2796 const Type *SrcTy = I.getOperand(0)->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002797 if (isFPIntBitCast(I)) {
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002798 Out << '(';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002799 // These int<->float and long<->double casts need to be handled specially
2800 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2801 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2802 writeOperand(I.getOperand(0));
2803 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2804 << getFloatBitCastField(I.getType());
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002805 Out << ')';
2806 return;
2807 }
2808
2809 Out << '(';
2810 printCast(I.getOpcode(), SrcTy, DstTy);
2811
2812 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
2813 if (SrcTy == Type::Int1Ty && I.getOpcode() == Instruction::SExt)
2814 Out << "0-";
2815
2816 writeOperand(I.getOperand(0));
2817
2818 if (DstTy == Type::Int1Ty &&
2819 (I.getOpcode() == Instruction::Trunc ||
2820 I.getOpcode() == Instruction::FPToUI ||
2821 I.getOpcode() == Instruction::FPToSI ||
2822 I.getOpcode() == Instruction::PtrToInt)) {
2823 // Make sure we really get a trunc to bool by anding the operand with 1
2824 Out << "&1u";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002825 }
2826 Out << ')';
2827}
2828
2829void CWriter::visitSelectInst(SelectInst &I) {
2830 Out << "((";
2831 writeOperand(I.getCondition());
2832 Out << ") ? (";
2833 writeOperand(I.getTrueValue());
2834 Out << ") : (";
2835 writeOperand(I.getFalseValue());
2836 Out << "))";
2837}
2838
2839
2840void CWriter::lowerIntrinsics(Function &F) {
2841 // This is used to keep track of intrinsics that get generated to a lowered
2842 // function. We must generate the prototypes before the function body which
2843 // will only be expanded on first use (by the loop below).
2844 std::vector<Function*> prototypesToGen;
2845
2846 // Examine all the instructions in this function to find the intrinsics that
2847 // need to be lowered.
2848 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2849 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2850 if (CallInst *CI = dyn_cast<CallInst>(I++))
2851 if (Function *F = CI->getCalledFunction())
2852 switch (F->getIntrinsicID()) {
2853 case Intrinsic::not_intrinsic:
Andrew Lenharth0531ec52008-02-16 14:46:26 +00002854 case Intrinsic::memory_barrier:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002855 case Intrinsic::vastart:
2856 case Intrinsic::vacopy:
2857 case Intrinsic::vaend:
2858 case Intrinsic::returnaddress:
2859 case Intrinsic::frameaddress:
2860 case Intrinsic::setjmp:
2861 case Intrinsic::longjmp:
2862 case Intrinsic::prefetch:
2863 case Intrinsic::dbg_stoppoint:
Dale Johannesenc339d8e2007-10-02 17:43:59 +00002864 case Intrinsic::powi:
Chris Lattner6a947cb2008-03-02 08:47:13 +00002865 case Intrinsic::x86_sse_cmp_ss:
2866 case Intrinsic::x86_sse_cmp_ps:
2867 case Intrinsic::x86_sse2_cmp_sd:
2868 case Intrinsic::x86_sse2_cmp_pd:
Chris Lattner709df322008-03-02 08:54:27 +00002869 case Intrinsic::ppc_altivec_lvsl:
Chris Lattner6a947cb2008-03-02 08:47:13 +00002870 // We directly implement these intrinsics
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002871 break;
2872 default:
2873 // If this is an intrinsic that directly corresponds to a GCC
2874 // builtin, we handle it.
2875 const char *BuiltinName = "";
2876#define GET_GCC_BUILTIN_NAME
2877#include "llvm/Intrinsics.gen"
2878#undef GET_GCC_BUILTIN_NAME
2879 // If we handle it, don't lower it.
2880 if (BuiltinName[0]) break;
2881
2882 // All other intrinsic calls we must lower.
2883 Instruction *Before = 0;
2884 if (CI != &BB->front())
2885 Before = prior(BasicBlock::iterator(CI));
2886
2887 IL->LowerIntrinsicCall(CI);
2888 if (Before) { // Move iterator to instruction after call
2889 I = Before; ++I;
2890 } else {
2891 I = BB->begin();
2892 }
2893 // If the intrinsic got lowered to another call, and that call has
2894 // a definition then we need to make sure its prototype is emitted
2895 // before any calls to it.
2896 if (CallInst *Call = dyn_cast<CallInst>(I))
2897 if (Function *NewF = Call->getCalledFunction())
2898 if (!NewF->isDeclaration())
2899 prototypesToGen.push_back(NewF);
2900
2901 break;
2902 }
2903
2904 // We may have collected some prototypes to emit in the loop above.
2905 // Emit them now, before the function that uses them is emitted. But,
2906 // be careful not to emit them twice.
2907 std::vector<Function*>::iterator I = prototypesToGen.begin();
2908 std::vector<Function*>::iterator E = prototypesToGen.end();
2909 for ( ; I != E; ++I) {
2910 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2911 Out << '\n';
2912 printFunctionSignature(*I, true);
2913 Out << ";\n";
2914 }
2915 }
2916}
2917
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002918void CWriter::visitCallInst(CallInst &I) {
Chris Lattner8a3b6e42008-05-22 06:19:37 +00002919 if (isa<InlineAsm>(I.getOperand(0)))
2920 return visitInlineAsm(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002921
2922 bool WroteCallee = false;
2923
2924 // Handle intrinsic function calls first...
2925 if (Function *F = I.getCalledFunction())
Chris Lattnera74b9182008-03-02 08:29:41 +00002926 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2927 if (visitBuiltinCall(I, ID, WroteCallee))
Andrew Lenharth0531ec52008-02-16 14:46:26 +00002928 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002929
2930 Value *Callee = I.getCalledValue();
2931
2932 const PointerType *PTy = cast<PointerType>(Callee->getType());
2933 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2934
2935 // If this is a call to a struct-return function, assign to the first
2936 // parameter instead of passing it to the call.
Devang Pateld222f862008-09-25 21:00:45 +00002937 const AttrListPtr &PAL = I.getAttributes();
Evan Chengb8a072c2008-01-12 18:53:07 +00002938 bool hasByVal = I.hasByValArgument();
Devang Patel949a4b72008-03-03 21:46:28 +00002939 bool isStructRet = I.hasStructRetAttr();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002940 if (isStructRet) {
Chris Lattner8bbc8592008-03-02 08:07:24 +00002941 writeOperandDeref(I.getOperand(1));
Evan Chengf8956382008-01-11 23:10:11 +00002942 Out << " = ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002943 }
2944
2945 if (I.isTailCall()) Out << " /*tail*/ ";
2946
2947 if (!WroteCallee) {
2948 // If this is an indirect call to a struct return function, we need to cast
Evan Chengb8a072c2008-01-12 18:53:07 +00002949 // the pointer. Ditto for indirect calls with byval arguments.
2950 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002951
2952 // GCC is a real PITA. It does not permit codegening casts of functions to
2953 // function pointers if they are in a call (it generates a trap instruction
2954 // instead!). We work around this by inserting a cast to void* in between
2955 // the function and the function pointer cast. Unfortunately, we can't just
2956 // form the constant expression here, because the folder will immediately
2957 // nuke it.
2958 //
2959 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2960 // that void* and function pointers have the same size. :( To deal with this
2961 // in the common case, we handle casts where the number of arguments passed
2962 // match exactly.
2963 //
2964 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2965 if (CE->isCast())
2966 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2967 NeedsCast = true;
2968 Callee = RF;
2969 }
2970
2971 if (NeedsCast) {
2972 // Ok, just cast the pointer type.
2973 Out << "((";
Evan Chengb8a072c2008-01-12 18:53:07 +00002974 if (isStructRet)
Duncan Sandsf5588dc2007-11-27 13:23:08 +00002975 printStructReturnPointerFunctionType(Out, PAL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002976 cast<PointerType>(I.getCalledValue()->getType()));
Evan Chengb8a072c2008-01-12 18:53:07 +00002977 else if (hasByVal)
2978 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
2979 else
2980 printType(Out, I.getCalledValue()->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002981 Out << ")(void*)";
2982 }
2983 writeOperand(Callee);
2984 if (NeedsCast) Out << ')';
2985 }
2986
2987 Out << '(';
2988
2989 unsigned NumDeclaredParams = FTy->getNumParams();
2990
2991 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2992 unsigned ArgNo = 0;
2993 if (isStructRet) { // Skip struct return argument.
2994 ++AI;
2995 ++ArgNo;
2996 }
2997
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002998 bool PrintedArg = false;
Evan Chengf8956382008-01-11 23:10:11 +00002999 for (; AI != AE; ++AI, ++ArgNo) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003000 if (PrintedArg) Out << ", ";
3001 if (ArgNo < NumDeclaredParams &&
3002 (*AI)->getType() != FTy->getParamType(ArgNo)) {
3003 Out << '(';
3004 printType(Out, FTy->getParamType(ArgNo),
Devang Pateld222f862008-09-25 21:00:45 +00003005 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003006 Out << ')';
3007 }
Evan Chengf8956382008-01-11 23:10:11 +00003008 // Check if the argument is expected to be passed by value.
Devang Pateld222f862008-09-25 21:00:45 +00003009 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
Chris Lattner8bbc8592008-03-02 08:07:24 +00003010 writeOperandDeref(*AI);
3011 else
3012 writeOperand(*AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003013 PrintedArg = true;
3014 }
3015 Out << ')';
3016}
3017
Chris Lattnera74b9182008-03-02 08:29:41 +00003018/// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3019/// if the entire call is handled, return false it it wasn't handled, and
3020/// optionally set 'WroteCallee' if the callee has already been printed out.
3021bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3022 bool &WroteCallee) {
3023 switch (ID) {
3024 default: {
3025 // If this is an intrinsic that directly corresponds to a GCC
3026 // builtin, we emit it here.
3027 const char *BuiltinName = "";
3028 Function *F = I.getCalledFunction();
3029#define GET_GCC_BUILTIN_NAME
3030#include "llvm/Intrinsics.gen"
3031#undef GET_GCC_BUILTIN_NAME
3032 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3033
3034 Out << BuiltinName;
3035 WroteCallee = true;
3036 return false;
3037 }
3038 case Intrinsic::memory_barrier:
Andrew Lenharth5c976182008-03-05 23:41:37 +00003039 Out << "__sync_synchronize()";
Chris Lattnera74b9182008-03-02 08:29:41 +00003040 return true;
3041 case Intrinsic::vastart:
3042 Out << "0; ";
3043
3044 Out << "va_start(*(va_list*)";
3045 writeOperand(I.getOperand(1));
3046 Out << ", ";
3047 // Output the last argument to the enclosing function.
3048 if (I.getParent()->getParent()->arg_empty()) {
Edwin Török4d9756a2009-07-08 20:53:28 +00003049 std::string msg;
3050 raw_string_ostream Msg(msg);
3051 Msg << "The C backend does not currently support zero "
Chris Lattnera74b9182008-03-02 08:29:41 +00003052 << "argument varargs functions, such as '"
Edwin Török4d9756a2009-07-08 20:53:28 +00003053 << I.getParent()->getParent()->getName() << "'!";
3054 llvm_report_error(Msg.str());
Chris Lattnera74b9182008-03-02 08:29:41 +00003055 }
3056 writeOperand(--I.getParent()->getParent()->arg_end());
3057 Out << ')';
3058 return true;
3059 case Intrinsic::vaend:
3060 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3061 Out << "0; va_end(*(va_list*)";
3062 writeOperand(I.getOperand(1));
3063 Out << ')';
3064 } else {
3065 Out << "va_end(*(va_list*)0)";
3066 }
3067 return true;
3068 case Intrinsic::vacopy:
3069 Out << "0; ";
3070 Out << "va_copy(*(va_list*)";
3071 writeOperand(I.getOperand(1));
3072 Out << ", *(va_list*)";
3073 writeOperand(I.getOperand(2));
3074 Out << ')';
3075 return true;
3076 case Intrinsic::returnaddress:
3077 Out << "__builtin_return_address(";
3078 writeOperand(I.getOperand(1));
3079 Out << ')';
3080 return true;
3081 case Intrinsic::frameaddress:
3082 Out << "__builtin_frame_address(";
3083 writeOperand(I.getOperand(1));
3084 Out << ')';
3085 return true;
3086 case Intrinsic::powi:
3087 Out << "__builtin_powi(";
3088 writeOperand(I.getOperand(1));
3089 Out << ", ";
3090 writeOperand(I.getOperand(2));
3091 Out << ')';
3092 return true;
3093 case Intrinsic::setjmp:
3094 Out << "setjmp(*(jmp_buf*)";
3095 writeOperand(I.getOperand(1));
3096 Out << ')';
3097 return true;
3098 case Intrinsic::longjmp:
3099 Out << "longjmp(*(jmp_buf*)";
3100 writeOperand(I.getOperand(1));
3101 Out << ", ";
3102 writeOperand(I.getOperand(2));
3103 Out << ')';
3104 return true;
3105 case Intrinsic::prefetch:
3106 Out << "LLVM_PREFETCH((const void *)";
3107 writeOperand(I.getOperand(1));
3108 Out << ", ";
3109 writeOperand(I.getOperand(2));
3110 Out << ", ";
3111 writeOperand(I.getOperand(3));
3112 Out << ")";
3113 return true;
3114 case Intrinsic::stacksave:
3115 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3116 // to work around GCC bugs (see PR1809).
3117 Out << "0; *((void**)&" << GetValueName(&I)
3118 << ") = __builtin_stack_save()";
3119 return true;
3120 case Intrinsic::dbg_stoppoint: {
3121 // If we use writeOperand directly we get a "u" suffix which is rejected
3122 // by gcc.
Owen Anderson847b99b2008-08-21 00:14:44 +00003123 std::stringstream SPIStr;
Chris Lattnera74b9182008-03-02 08:29:41 +00003124 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Owen Anderson847b99b2008-08-21 00:14:44 +00003125 SPI.getDirectory()->print(SPIStr);
Chris Lattnera74b9182008-03-02 08:29:41 +00003126 Out << "\n#line "
3127 << SPI.getLine()
Owen Anderson847b99b2008-08-21 00:14:44 +00003128 << " \"";
3129 Out << SPIStr.str();
3130 SPIStr.clear();
3131 SPI.getFileName()->print(SPIStr);
3132 Out << SPIStr.str() << "\"\n";
Chris Lattnera74b9182008-03-02 08:29:41 +00003133 return true;
3134 }
Chris Lattner6a947cb2008-03-02 08:47:13 +00003135 case Intrinsic::x86_sse_cmp_ss:
3136 case Intrinsic::x86_sse_cmp_ps:
3137 case Intrinsic::x86_sse2_cmp_sd:
3138 case Intrinsic::x86_sse2_cmp_pd:
3139 Out << '(';
3140 printType(Out, I.getType());
3141 Out << ')';
3142 // Multiple GCC builtins multiplex onto this intrinsic.
3143 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003144 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
Chris Lattner6a947cb2008-03-02 08:47:13 +00003145 case 0: Out << "__builtin_ia32_cmpeq"; break;
3146 case 1: Out << "__builtin_ia32_cmplt"; break;
3147 case 2: Out << "__builtin_ia32_cmple"; break;
3148 case 3: Out << "__builtin_ia32_cmpunord"; break;
3149 case 4: Out << "__builtin_ia32_cmpneq"; break;
3150 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3151 case 6: Out << "__builtin_ia32_cmpnle"; break;
3152 case 7: Out << "__builtin_ia32_cmpord"; break;
3153 }
3154 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3155 Out << 'p';
3156 else
3157 Out << 's';
3158 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3159 Out << 's';
3160 else
3161 Out << 'd';
3162
3163 Out << "(";
3164 writeOperand(I.getOperand(1));
3165 Out << ", ";
3166 writeOperand(I.getOperand(2));
3167 Out << ")";
3168 return true;
Chris Lattner709df322008-03-02 08:54:27 +00003169 case Intrinsic::ppc_altivec_lvsl:
3170 Out << '(';
3171 printType(Out, I.getType());
3172 Out << ')';
3173 Out << "__builtin_altivec_lvsl(0, (void*)";
3174 writeOperand(I.getOperand(1));
3175 Out << ")";
3176 return true;
Chris Lattnera74b9182008-03-02 08:29:41 +00003177 }
3178}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003179
3180//This converts the llvm constraint string to something gcc is expecting.
3181//TODO: work out platform independent constraints and factor those out
3182// of the per target tables
3183// handle multiple constraint codes
3184std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
3185
3186 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3187
Dan Gohman12300e12008-03-25 21:45:14 +00003188 const char *const *table = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003189
3190 //Grab the translation table from TargetAsmInfo if it exists
3191 if (!TAsm) {
3192 std::string E;
Gordon Henriksen99e34ab2007-10-17 21:28:48 +00003193 const TargetMachineRegistry::entry* Match =
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003194 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
3195 if (Match) {
3196 //Per platform Target Machines don't exist, so create it
3197 // this must be done only once
3198 const TargetMachine* TM = Match->CtorFn(*TheModule, "");
3199 TAsm = TM->getTargetAsmInfo();
3200 }
3201 }
3202 if (TAsm)
3203 table = TAsm->getAsmCBE();
3204
3205 //Search the translation table if it exists
3206 for (int i = 0; table && table[i]; i += 2)
3207 if (c.Codes[0] == table[i])
3208 return table[i+1];
3209
3210 //default is identity
3211 return c.Codes[0];
3212}
3213
3214//TODO: import logic from AsmPrinter.cpp
3215static std::string gccifyAsm(std::string asmstr) {
3216 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3217 if (asmstr[i] == '\n')
3218 asmstr.replace(i, 1, "\\n");
3219 else if (asmstr[i] == '\t')
3220 asmstr.replace(i, 1, "\\t");
3221 else if (asmstr[i] == '$') {
3222 if (asmstr[i + 1] == '{') {
3223 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3224 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3225 std::string n = "%" +
3226 asmstr.substr(a + 1, b - a - 1) +
3227 asmstr.substr(i + 2, a - i - 2);
3228 asmstr.replace(i, b - i + 1, n);
3229 i += n.size() - 1;
3230 } else
3231 asmstr.replace(i, 1, "%");
3232 }
3233 else if (asmstr[i] == '%')//grr
3234 { asmstr.replace(i, 1, "%%"); ++i;}
3235
3236 return asmstr;
3237}
3238
3239//TODO: assumptions about what consume arguments from the call are likely wrong
3240// handle communitivity
3241void CWriter::visitInlineAsm(CallInst &CI) {
3242 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
3243 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
Chris Lattner8a3b6e42008-05-22 06:19:37 +00003244
3245 std::vector<std::pair<Value*, int> > ResultVals;
3246 if (CI.getType() == Type::VoidTy)
3247 ;
3248 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3249 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3250 ResultVals.push_back(std::make_pair(&CI, (int)i));
3251 } else {
3252 ResultVals.push_back(std::make_pair(&CI, -1));
3253 }
3254
Chris Lattnera605a9c2008-06-04 18:03:28 +00003255 // Fix up the asm string for gcc and emit it.
3256 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3257 Out << " :";
3258
3259 unsigned ValueCount = 0;
3260 bool IsFirst = true;
3261
3262 // Convert over all the output constraints.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003263 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
Chris Lattnera605a9c2008-06-04 18:03:28 +00003264 E = Constraints.end(); I != E; ++I) {
3265
3266 if (I->Type != InlineAsm::isOutput) {
3267 ++ValueCount;
3268 continue; // Ignore non-output constraints.
3269 }
3270
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003271 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
Chris Lattner8a3b6e42008-05-22 06:19:37 +00003272 std::string C = InterpretASMConstraint(*I);
3273 if (C.empty()) continue;
3274
Chris Lattnera605a9c2008-06-04 18:03:28 +00003275 if (!IsFirst) {
Chris Lattner8a3b6e42008-05-22 06:19:37 +00003276 Out << ", ";
Chris Lattnera605a9c2008-06-04 18:03:28 +00003277 IsFirst = false;
3278 }
3279
3280 // Unpack the dest.
3281 Value *DestVal;
3282 int DestValNo = -1;
3283
3284 if (ValueCount < ResultVals.size()) {
3285 DestVal = ResultVals[ValueCount].first;
3286 DestValNo = ResultVals[ValueCount].second;
3287 } else
3288 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3289
3290 if (I->isEarlyClobber)
3291 C = "&"+C;
3292
3293 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3294 if (DestValNo != -1)
3295 Out << ".field" << DestValNo; // Multiple retvals.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003296 Out << ")";
Chris Lattnera605a9c2008-06-04 18:03:28 +00003297 ++ValueCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003298 }
Chris Lattnera605a9c2008-06-04 18:03:28 +00003299
3300
3301 // Convert over all the input constraints.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003302 Out << "\n :";
Chris Lattnera605a9c2008-06-04 18:03:28 +00003303 IsFirst = true;
3304 ValueCount = 0;
3305 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3306 E = Constraints.end(); I != E; ++I) {
3307 if (I->Type != InlineAsm::isInput) {
3308 ++ValueCount;
3309 continue; // Ignore non-input constraints.
3310 }
3311
3312 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3313 std::string C = InterpretASMConstraint(*I);
3314 if (C.empty()) continue;
3315
3316 if (!IsFirst) {
Chris Lattner5fee1202008-05-22 06:29:38 +00003317 Out << ", ";
Chris Lattnera605a9c2008-06-04 18:03:28 +00003318 IsFirst = false;
3319 }
3320
3321 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3322 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3323
3324 Out << "\"" << C << "\"(";
3325 if (!I->isIndirect)
3326 writeOperand(SrcVal);
3327 else
3328 writeOperandDeref(SrcVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003329 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003330 }
Chris Lattnera605a9c2008-06-04 18:03:28 +00003331
3332 // Convert over the clobber constraints.
3333 IsFirst = true;
3334 ValueCount = 0;
3335 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3336 E = Constraints.end(); I != E; ++I) {
3337 if (I->Type != InlineAsm::isClobber)
3338 continue; // Ignore non-input constraints.
3339
3340 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3341 std::string C = InterpretASMConstraint(*I);
3342 if (C.empty()) continue;
3343
3344 if (!IsFirst) {
3345 Out << ", ";
3346 IsFirst = false;
3347 }
3348
3349 Out << '\"' << C << '"';
3350 }
3351
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003352 Out << ")";
3353}
3354
3355void CWriter::visitMallocInst(MallocInst &I) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003356 llvm_unreachable("lowerallocations pass didn't work!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003357}
3358
3359void CWriter::visitAllocaInst(AllocaInst &I) {
3360 Out << '(';
3361 printType(Out, I.getType());
3362 Out << ") alloca(sizeof(";
3363 printType(Out, I.getType()->getElementType());
3364 Out << ')';
3365 if (I.isArrayAllocation()) {
3366 Out << " * " ;
3367 writeOperand(I.getOperand(0));
3368 }
3369 Out << ')';
3370}
3371
3372void CWriter::visitFreeInst(FreeInst &I) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003373 llvm_unreachable("lowerallocations pass didn't work!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003374}
3375
Chris Lattner8bbc8592008-03-02 08:07:24 +00003376void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohmanad831302008-07-24 17:57:48 +00003377 gep_type_iterator E, bool Static) {
Chris Lattner8bbc8592008-03-02 08:07:24 +00003378
3379 // If there are no indices, just print out the pointer.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003380 if (I == E) {
Chris Lattner8bbc8592008-03-02 08:07:24 +00003381 writeOperand(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003382 return;
3383 }
Chris Lattner8bbc8592008-03-02 08:07:24 +00003384
3385 // Find out if the last index is into a vector. If so, we have to print this
3386 // specially. Since vectors can't have elements of indexable type, only the
3387 // last index could possibly be of a vector element.
3388 const VectorType *LastIndexIsVector = 0;
3389 {
3390 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3391 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003392 }
Chris Lattner8bbc8592008-03-02 08:07:24 +00003393
3394 Out << "(";
3395
3396 // If the last index is into a vector, we can't print it as &a[i][j] because
3397 // we can't index into a vector with j in GCC. Instead, emit this as
3398 // (((float*)&a[i])+j)
3399 if (LastIndexIsVector) {
3400 Out << "((";
3401 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3402 Out << ")(";
3403 }
3404
3405 Out << '&';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003406
Chris Lattner8bbc8592008-03-02 08:07:24 +00003407 // If the first index is 0 (very typical) we can do a number of
3408 // simplifications to clean up the code.
3409 Value *FirstOp = I.getOperand();
3410 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3411 // First index isn't simple, print it the hard way.
3412 writeOperand(Ptr);
3413 } else {
3414 ++I; // Skip the zero index.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003415
Chris Lattner8bbc8592008-03-02 08:07:24 +00003416 // Okay, emit the first operand. If Ptr is something that is already address
3417 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3418 if (isAddressExposed(Ptr)) {
Dan Gohmanad831302008-07-24 17:57:48 +00003419 writeOperandInternal(Ptr, Static);
Chris Lattner8bbc8592008-03-02 08:07:24 +00003420 } else if (I != E && isa<StructType>(*I)) {
3421 // If we didn't already emit the first operand, see if we can print it as
3422 // P->f instead of "P[0].f"
3423 writeOperand(Ptr);
3424 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3425 ++I; // eat the struct index as well.
3426 } else {
3427 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3428 Out << "(*";
3429 writeOperand(Ptr);
3430 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003431 }
3432 }
3433
Chris Lattner8bbc8592008-03-02 08:07:24 +00003434 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003435 if (isa<StructType>(*I)) {
3436 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
Dan Gohman5d995b02008-06-02 21:30:49 +00003437 } else if (isa<ArrayType>(*I)) {
3438 Out << ".array[";
3439 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3440 Out << ']';
Chris Lattner8bbc8592008-03-02 08:07:24 +00003441 } else if (!isa<VectorType>(*I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003442 Out << '[';
Chris Lattner7ce1ee42007-09-22 20:16:48 +00003443 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003444 Out << ']';
Chris Lattner8bbc8592008-03-02 08:07:24 +00003445 } else {
3446 // If the last index is into a vector, then print it out as "+j)". This
3447 // works with the 'LastIndexIsVector' code above.
3448 if (isa<Constant>(I.getOperand()) &&
3449 cast<Constant>(I.getOperand())->isNullValue()) {
3450 Out << "))"; // avoid "+0".
3451 } else {
3452 Out << ")+(";
3453 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3454 Out << "))";
3455 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003456 }
Chris Lattner8bbc8592008-03-02 08:07:24 +00003457 }
3458 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003459}
3460
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003461void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3462 bool IsVolatile, unsigned Alignment) {
3463
3464 bool IsUnaligned = Alignment &&
3465 Alignment < TD->getABITypeAlignment(OperandType);
3466
3467 if (!IsUnaligned)
3468 Out << '*';
3469 if (IsVolatile || IsUnaligned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003470 Out << "((";
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003471 if (IsUnaligned)
3472 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3473 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3474 if (IsUnaligned) {
3475 Out << "; } ";
3476 if (IsVolatile) Out << "volatile ";
3477 Out << "*";
3478 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003479 Out << ")";
3480 }
3481
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003482 writeOperand(Operand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003483
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003484 if (IsVolatile || IsUnaligned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003485 Out << ')';
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003486 if (IsUnaligned)
3487 Out << "->data";
3488 }
3489}
3490
3491void CWriter::visitLoadInst(LoadInst &I) {
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003492 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3493 I.getAlignment());
3494
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003495}
3496
3497void CWriter::visitStoreInst(StoreInst &I) {
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003498 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3499 I.isVolatile(), I.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003500 Out << " = ";
3501 Value *Operand = I.getOperand(0);
3502 Constant *BitMask = 0;
3503 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3504 if (!ITy->isPowerOf2ByteWidth())
3505 // We have a bit width that doesn't match an even power-of-2 byte
3506 // size. Consequently we must & the value with the type's bit mask
Owen Anderson9f5b2aa2009-07-14 23:09:55 +00003507 BitMask = Context->getConstantInt(ITy, ITy->getBitMask());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003508 if (BitMask)
3509 Out << "((";
3510 writeOperand(Operand);
3511 if (BitMask) {
3512 Out << ") & ";
Dan Gohmanad831302008-07-24 17:57:48 +00003513 printConstant(BitMask, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003514 Out << ")";
3515 }
3516}
3517
3518void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner8bbc8592008-03-02 08:07:24 +00003519 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
Dan Gohmanad831302008-07-24 17:57:48 +00003520 gep_type_end(I), false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003521}
3522
3523void CWriter::visitVAArgInst(VAArgInst &I) {
3524 Out << "va_arg(*(va_list*)";
3525 writeOperand(I.getOperand(0));
3526 Out << ", ";
3527 printType(Out, I.getType());
3528 Out << ");\n ";
3529}
3530
Chris Lattnerf41a7942008-03-02 03:52:39 +00003531void CWriter::visitInsertElementInst(InsertElementInst &I) {
3532 const Type *EltTy = I.getType()->getElementType();
3533 writeOperand(I.getOperand(0));
3534 Out << ";\n ";
3535 Out << "((";
3536 printType(Out, PointerType::getUnqual(EltTy));
3537 Out << ")(&" << GetValueName(&I) << "))[";
Chris Lattnerf41a7942008-03-02 03:52:39 +00003538 writeOperand(I.getOperand(2));
Chris Lattner09418362008-03-02 08:10:16 +00003539 Out << "] = (";
3540 writeOperand(I.getOperand(1));
Chris Lattnerf41a7942008-03-02 03:52:39 +00003541 Out << ")";
3542}
3543
Chris Lattnera5f0bc02008-03-02 03:57:08 +00003544void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3545 // We know that our operand is not inlined.
3546 Out << "((";
3547 const Type *EltTy =
3548 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3549 printType(Out, PointerType::getUnqual(EltTy));
3550 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3551 writeOperand(I.getOperand(1));
3552 Out << "]";
3553}
3554
Chris Lattnerf858a042008-03-02 05:41:07 +00003555void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3556 Out << "(";
3557 printType(Out, SVI.getType());
3558 Out << "){ ";
3559 const VectorType *VT = SVI.getType();
3560 unsigned NumElts = VT->getNumElements();
3561 const Type *EltTy = VT->getElementType();
3562
3563 for (unsigned i = 0; i != NumElts; ++i) {
3564 if (i) Out << ", ";
3565 int SrcVal = SVI.getMaskValue(i);
3566 if ((unsigned)SrcVal >= NumElts*2) {
3567 Out << " 0/*undef*/ ";
3568 } else {
3569 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3570 if (isa<Instruction>(Op)) {
3571 // Do an extractelement of this value from the appropriate input.
3572 Out << "((";
3573 printType(Out, PointerType::getUnqual(EltTy));
3574 Out << ")(&" << GetValueName(Op)
Duncan Sandsf6890712008-05-27 11:50:51 +00003575 << "))[" << (SrcVal & (NumElts-1)) << "]";
Chris Lattnerf858a042008-03-02 05:41:07 +00003576 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3577 Out << "0";
3578 } else {
Duncan Sandsf6890712008-05-27 11:50:51 +00003579 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
Dan Gohmanad831302008-07-24 17:57:48 +00003580 (NumElts-1)),
3581 false);
Chris Lattnerf858a042008-03-02 05:41:07 +00003582 }
3583 }
3584 }
3585 Out << "}";
3586}
Chris Lattnera5f0bc02008-03-02 03:57:08 +00003587
Dan Gohman5d995b02008-06-02 21:30:49 +00003588void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3589 // Start by copying the entire aggregate value into the result variable.
3590 writeOperand(IVI.getOperand(0));
3591 Out << ";\n ";
3592
3593 // Then do the insert to update the field.
3594 Out << GetValueName(&IVI);
3595 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3596 i != e; ++i) {
3597 const Type *IndexedTy =
3598 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3599 if (isa<ArrayType>(IndexedTy))
3600 Out << ".array[" << *i << "]";
3601 else
3602 Out << ".field" << *i;
3603 }
3604 Out << " = ";
3605 writeOperand(IVI.getOperand(1));
3606}
3607
3608void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3609 Out << "(";
3610 if (isa<UndefValue>(EVI.getOperand(0))) {
3611 Out << "(";
3612 printType(Out, EVI.getType());
3613 Out << ") 0/*UNDEF*/";
3614 } else {
3615 Out << GetValueName(EVI.getOperand(0));
3616 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3617 i != e; ++i) {
3618 const Type *IndexedTy =
3619 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3620 if (isa<ArrayType>(IndexedTy))
3621 Out << ".array[" << *i << "]";
3622 else
3623 Out << ".field" << *i;
3624 }
3625 }
3626 Out << ")";
3627}
3628
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003629//===----------------------------------------------------------------------===//
3630// External Interface declaration
3631//===----------------------------------------------------------------------===//
3632
3633bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
David Greene302008d2009-07-14 20:18:05 +00003634 formatted_raw_ostream &o,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003635 CodeGenFileType FileType,
Bill Wendling5ed22ac2009-04-29 23:29:43 +00003636 CodeGenOpt::Level OptLevel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003637 if (FileType != TargetMachine::AssemblyFile) return true;
3638
Gordon Henriksendf87fdc2008-01-07 01:30:38 +00003639 PM.add(createGCLoweringPass());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003640 PM.add(createLowerAllocationsPass(true));
3641 PM.add(createLowerInvokePass());
3642 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3643 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3644 PM.add(new CWriter(o));
Gordon Henriksen1aed5992008-08-17 18:44:35 +00003645 PM.add(createGCInfoDeleter());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003646 return false;
3647}