1 //===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library converts LLVM code to C code, compilable by GCC and other C
13 //===----------------------------------------------------------------------===//
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"
21 #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"
30 #include "llvm/CodeGen/Passes.h"
31 #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"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/FormattedStream.h"
40 #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"
52 /// 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
57 extern "C" int CBackendTargetMachineModule;
58 int CBackendTargetMachineModule = 0;
60 // Register the target.
61 static RegisterTarget<CTargetMachine> X("c", "C backend");
63 // Force static initialization.
64 extern "C" void LLVMInitializeCBackendTarget() { }
67 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
68 /// any unnamed structure types that are used by the program, and merges
69 /// external functions with the same name.
71 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
74 CBackendNameAllUsedStructsAndMergeFunctions()
76 void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.addRequired<FindUsedTypes>();
80 virtual const char *getPassName() const {
81 return "C backend type canonicalizer";
84 virtual bool runOnModule(Module &M);
87 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
89 /// CWriter - This class is the main chunk of code that converts an LLVM
90 /// module to a C translation unit.
91 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
92 formatted_raw_ostream &Out;
93 IntrinsicLowering *IL;
96 const Module *TheModule;
97 const TargetAsmInfo* TAsm;
99 std::map<const Type *, std::string> TypeNames;
100 std::map<const ConstantFP *, unsigned> FPConstantMap;
101 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
102 std::set<const Argument*> ByValParams;
104 unsigned OpaqueCounter;
105 DenseMap<const Value*, unsigned> AnonValueNumbers;
106 unsigned NextAnonValueNumber;
110 explicit CWriter(formatted_raw_ostream &o)
111 : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0),
112 TheModule(0), TAsm(0), TD(0), OpaqueCounter(0), NextAnonValueNumber(0) {
116 virtual const char *getPassName() const { return "C backend"; }
118 void getAnalysisUsage(AnalysisUsage &AU) const {
119 AU.addRequired<LoopInfo>();
120 AU.setPreservesAll();
123 virtual bool doInitialization(Module &M);
125 bool runOnFunction(Function &F) {
126 // Do not codegen any 'available_externally' functions at all, they have
127 // definitions outside the translation unit.
128 if (F.hasAvailableExternallyLinkage())
131 LI = &getAnalysis<LoopInfo>();
133 // Get rid of intrinsics we can't handle.
136 // Output all floating point constants that cannot be printed accurately.
137 printFloatingPointConstants(F);
143 virtual bool doFinalization(Module &M) {
148 FPConstantMap.clear();
151 intrinsicPrototypesAlreadyGenerated.clear();
155 raw_ostream &printType(formatted_raw_ostream &Out,
157 bool isSigned = false,
158 const std::string &VariableName = "",
159 bool IgnoreName = false,
160 const AttrListPtr &PAL = AttrListPtr());
161 std::ostream &printType(std::ostream &Out, const Type *Ty,
162 bool isSigned = false,
163 const std::string &VariableName = "",
164 bool IgnoreName = false,
165 const AttrListPtr &PAL = AttrListPtr());
166 raw_ostream &printSimpleType(formatted_raw_ostream &Out,
169 const std::string &NameSoFar = "");
170 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
172 const std::string &NameSoFar = "");
174 void printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
175 const AttrListPtr &PAL,
176 const PointerType *Ty);
178 /// writeOperandDeref - Print the result of dereferencing the specified
179 /// operand with '*'. This is equivalent to printing '*' then using
180 /// writeOperand, but avoids excess syntax in some cases.
181 void writeOperandDeref(Value *Operand) {
182 if (isAddressExposed(Operand)) {
183 // Already something with an address exposed.
184 writeOperandInternal(Operand);
187 writeOperand(Operand);
192 void writeOperand(Value *Operand, bool Static = false);
193 void writeInstComputationInline(Instruction &I);
194 void writeOperandInternal(Value *Operand, bool Static = false);
195 void writeOperandWithCast(Value* Operand, unsigned Opcode);
196 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
197 bool writeInstructionCast(const Instruction &I);
199 void writeMemoryAccess(Value *Operand, const Type *OperandType,
200 bool IsVolatile, unsigned Alignment);
203 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
205 void lowerIntrinsics(Function &F);
207 void printModule(Module *M);
208 void printModuleTypes(const TypeSymbolTable &ST);
209 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
210 void printFloatingPointConstants(Function &F);
211 void printFloatingPointConstants(const Constant *C);
212 void printFunctionSignature(const Function *F, bool Prototype);
214 void printFunction(Function &);
215 void printBasicBlock(BasicBlock *BB);
216 void printLoop(Loop *L);
218 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
219 void printConstant(Constant *CPV, bool Static);
220 void printConstantWithCast(Constant *CPV, unsigned Opcode);
221 bool printConstExprCast(const ConstantExpr *CE, bool Static);
222 void printConstantArray(ConstantArray *CPA, bool Static);
223 void printConstantVector(ConstantVector *CV, bool Static);
225 /// isAddressExposed - Return true if the specified value's name needs to
226 /// have its address taken in order to get a C value of the correct type.
227 /// This happens for global variables, byval parameters, and direct allocas.
228 bool isAddressExposed(const Value *V) const {
229 if (const Argument *A = dyn_cast<Argument>(V))
230 return ByValParams.count(A);
231 return isa<GlobalVariable>(V) || isDirectAlloca(V);
234 // isInlinableInst - Attempt to inline instructions into their uses to build
235 // trees as much as possible. To do this, we have to consistently decide
236 // what is acceptable to inline, so that variable declarations don't get
237 // printed and an extra copy of the expr is not emitted.
239 static bool isInlinableInst(const Instruction &I) {
240 // Always inline cmp instructions, even if they are shared by multiple
241 // expressions. GCC generates horrible code if we don't.
245 // Must be an expression, must be used exactly once. If it is dead, we
246 // emit it inline where it would go.
247 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
248 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
249 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
250 isa<InsertValueInst>(I))
251 // Don't inline a load across a store or other bad things!
254 // Must not be used in inline asm, extractelement, or shufflevector.
256 const Instruction &User = cast<Instruction>(*I.use_back());
257 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
258 isa<ShuffleVectorInst>(User))
262 // Only inline instruction it if it's use is in the same BB as the inst.
263 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
266 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
267 // variables which are accessed with the & operator. This causes GCC to
268 // generate significantly better code than to emit alloca calls directly.
270 static const AllocaInst *isDirectAlloca(const Value *V) {
271 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
272 if (!AI) return false;
273 if (AI->isArrayAllocation())
274 return 0; // FIXME: we can also inline fixed size array allocas!
275 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
280 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
281 static bool isInlineAsm(const Instruction& I) {
282 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
287 // Instruction visitation functions
288 friend class InstVisitor<CWriter>;
290 void visitReturnInst(ReturnInst &I);
291 void visitBranchInst(BranchInst &I);
292 void visitSwitchInst(SwitchInst &I);
293 void visitInvokeInst(InvokeInst &I) {
294 llvm_unreachable("Lowerinvoke pass didn't work!");
297 void visitUnwindInst(UnwindInst &I) {
298 llvm_unreachable("Lowerinvoke pass didn't work!");
300 void visitUnreachableInst(UnreachableInst &I);
302 void visitPHINode(PHINode &I);
303 void visitBinaryOperator(Instruction &I);
304 void visitICmpInst(ICmpInst &I);
305 void visitFCmpInst(FCmpInst &I);
307 void visitCastInst (CastInst &I);
308 void visitSelectInst(SelectInst &I);
309 void visitCallInst (CallInst &I);
310 void visitInlineAsm(CallInst &I);
311 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
313 void visitMallocInst(MallocInst &I);
314 void visitAllocaInst(AllocaInst &I);
315 void visitFreeInst (FreeInst &I);
316 void visitLoadInst (LoadInst &I);
317 void visitStoreInst (StoreInst &I);
318 void visitGetElementPtrInst(GetElementPtrInst &I);
319 void visitVAArgInst (VAArgInst &I);
321 void visitInsertElementInst(InsertElementInst &I);
322 void visitExtractElementInst(ExtractElementInst &I);
323 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
325 void visitInsertValueInst(InsertValueInst &I);
326 void visitExtractValueInst(ExtractValueInst &I);
328 void visitInstruction(Instruction &I) {
330 cerr << "C Writer does not know about " << I;
335 void outputLValue(Instruction *I) {
336 Out << " " << GetValueName(I) << " = ";
339 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
340 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
341 BasicBlock *Successor, unsigned Indent);
342 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
344 void printGEPExpression(Value *Ptr, gep_type_iterator I,
345 gep_type_iterator E, bool Static);
347 std::string GetValueName(const Value *Operand);
351 char CWriter::ID = 0;
353 /// This method inserts names for any unnamed structure types that are used by
354 /// the program, and removes names from structure types that are not used by the
357 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
358 // Get a set of types that are used by the program...
359 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
361 // Loop over the module symbol table, removing types from UT that are
362 // already named, and removing names for types that are not used.
364 TypeSymbolTable &TST = M.getTypeSymbolTable();
365 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
367 TypeSymbolTable::iterator I = TI++;
369 // If this isn't a struct or array type, remove it from our set of types
370 // to name. This simplifies emission later.
371 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
372 !isa<ArrayType>(I->second)) {
375 // If this is not used, remove it from the symbol table.
376 std::set<const Type *>::iterator UTI = UT.find(I->second);
380 UT.erase(UTI); // Only keep one name for this type.
384 // UT now contains types that are not named. Loop over it, naming
387 bool Changed = false;
388 unsigned RenameCounter = 0;
389 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
391 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
392 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
398 // Loop over all external functions and globals. If we have two with
399 // identical names, merge them.
400 // FIXME: This code should disappear when we don't allow values with the same
401 // names when they have different types!
402 std::map<std::string, GlobalValue*> ExtSymbols;
403 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
405 if (GV->isDeclaration() && GV->hasName()) {
406 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
407 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
409 // Found a conflict, replace this global with the previous one.
410 GlobalValue *OldGV = X.first->second;
411 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
412 GV->eraseFromParent();
417 // Do the same for globals.
418 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
420 GlobalVariable *GV = I++;
421 if (GV->isDeclaration() && GV->hasName()) {
422 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
423 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
425 // Found a conflict, replace this global with the previous one.
426 GlobalValue *OldGV = X.first->second;
427 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
428 GV->eraseFromParent();
437 /// printStructReturnPointerFunctionType - This is like printType for a struct
438 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
439 /// print it as "Struct (*)(...)", for struct return functions.
440 void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
441 const AttrListPtr &PAL,
442 const PointerType *TheTy) {
443 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
444 std::stringstream FunctionInnards;
445 FunctionInnards << " (*) (";
446 bool PrintedType = false;
448 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
449 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
451 for (++I, ++Idx; I != E; ++I, ++Idx) {
453 FunctionInnards << ", ";
454 const Type *ArgTy = *I;
455 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
456 assert(isa<PointerType>(ArgTy));
457 ArgTy = cast<PointerType>(ArgTy)->getElementType();
459 printType(FunctionInnards, ArgTy,
460 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
463 if (FTy->isVarArg()) {
465 FunctionInnards << ", ...";
466 } else if (!PrintedType) {
467 FunctionInnards << "void";
469 FunctionInnards << ')';
470 std::string tstr = FunctionInnards.str();
471 printType(Out, RetTy,
472 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
476 CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
478 const std::string &NameSoFar) {
479 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
480 "Invalid type for printSimpleType");
481 switch (Ty->getTypeID()) {
482 case Type::VoidTyID: return Out << "void " << NameSoFar;
483 case Type::IntegerTyID: {
484 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
486 return Out << "bool " << NameSoFar;
487 else if (NumBits <= 8)
488 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
489 else if (NumBits <= 16)
490 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
491 else if (NumBits <= 32)
492 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
493 else if (NumBits <= 64)
494 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
496 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
497 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
500 case Type::FloatTyID: return Out << "float " << NameSoFar;
501 case Type::DoubleTyID: return Out << "double " << NameSoFar;
502 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
503 // present matches host 'long double'.
504 case Type::X86_FP80TyID:
505 case Type::PPC_FP128TyID:
506 case Type::FP128TyID: return Out << "long double " << NameSoFar;
508 case Type::VectorTyID: {
509 const VectorType *VTy = cast<VectorType>(Ty);
510 return printSimpleType(Out, VTy->getElementType(), isSigned,
511 " __attribute__((vector_size(" +
512 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
517 cerr << "Unknown primitive type: " << *Ty << "\n";
524 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
525 const std::string &NameSoFar) {
526 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
527 "Invalid type for printSimpleType");
528 switch (Ty->getTypeID()) {
529 case Type::VoidTyID: return Out << "void " << NameSoFar;
530 case Type::IntegerTyID: {
531 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
533 return Out << "bool " << NameSoFar;
534 else if (NumBits <= 8)
535 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
536 else if (NumBits <= 16)
537 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
538 else if (NumBits <= 32)
539 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
540 else if (NumBits <= 64)
541 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
543 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
544 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
547 case Type::FloatTyID: return Out << "float " << NameSoFar;
548 case Type::DoubleTyID: return Out << "double " << NameSoFar;
549 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
550 // present matches host 'long double'.
551 case Type::X86_FP80TyID:
552 case Type::PPC_FP128TyID:
553 case Type::FP128TyID: return Out << "long double " << NameSoFar;
555 case Type::VectorTyID: {
556 const VectorType *VTy = cast<VectorType>(Ty);
557 return printSimpleType(Out, VTy->getElementType(), isSigned,
558 " __attribute__((vector_size(" +
559 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
564 cerr << "Unknown primitive type: " << *Ty << "\n";
570 // Pass the Type* and the variable name and this prints out the variable
573 raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
575 bool isSigned, const std::string &NameSoFar,
576 bool IgnoreName, const AttrListPtr &PAL) {
577 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
578 printSimpleType(Out, Ty, isSigned, NameSoFar);
582 // Check to see if the type is named.
583 if (!IgnoreName || isa<OpaqueType>(Ty)) {
584 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
585 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
588 switch (Ty->getTypeID()) {
589 case Type::FunctionTyID: {
590 const FunctionType *FTy = cast<FunctionType>(Ty);
591 std::stringstream FunctionInnards;
592 FunctionInnards << " (" << NameSoFar << ") (";
594 for (FunctionType::param_iterator I = FTy->param_begin(),
595 E = FTy->param_end(); I != E; ++I) {
596 const Type *ArgTy = *I;
597 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
598 assert(isa<PointerType>(ArgTy));
599 ArgTy = cast<PointerType>(ArgTy)->getElementType();
601 if (I != FTy->param_begin())
602 FunctionInnards << ", ";
603 printType(FunctionInnards, ArgTy,
604 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
607 if (FTy->isVarArg()) {
608 if (FTy->getNumParams())
609 FunctionInnards << ", ...";
610 } else if (!FTy->getNumParams()) {
611 FunctionInnards << "void";
613 FunctionInnards << ')';
614 std::string tstr = FunctionInnards.str();
615 printType(Out, FTy->getReturnType(),
616 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
619 case Type::StructTyID: {
620 const StructType *STy = cast<StructType>(Ty);
621 Out << NameSoFar + " {\n";
623 for (StructType::element_iterator I = STy->element_begin(),
624 E = STy->element_end(); I != E; ++I) {
626 printType(Out, *I, false, "field" + utostr(Idx++));
631 Out << " __attribute__ ((packed))";
635 case Type::PointerTyID: {
636 const PointerType *PTy = cast<PointerType>(Ty);
637 std::string ptrName = "*" + NameSoFar;
639 if (isa<ArrayType>(PTy->getElementType()) ||
640 isa<VectorType>(PTy->getElementType()))
641 ptrName = "(" + ptrName + ")";
644 // Must be a function ptr cast!
645 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
646 return printType(Out, PTy->getElementType(), false, ptrName);
649 case Type::ArrayTyID: {
650 const ArrayType *ATy = cast<ArrayType>(Ty);
651 unsigned NumElements = ATy->getNumElements();
652 if (NumElements == 0) NumElements = 1;
653 // Arrays are wrapped in structs to allow them to have normal
654 // value semantics (avoiding the array "decay").
655 Out << NameSoFar << " { ";
656 printType(Out, ATy->getElementType(), false,
657 "array[" + utostr(NumElements) + "]");
661 case Type::OpaqueTyID: {
662 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
663 assert(TypeNames.find(Ty) == TypeNames.end());
664 TypeNames[Ty] = TyName;
665 return Out << TyName << ' ' << NameSoFar;
668 llvm_unreachable("Unhandled case in getTypeProps!");
674 // Pass the Type* and the variable name and this prints out the variable
677 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
678 bool isSigned, const std::string &NameSoFar,
679 bool IgnoreName, const AttrListPtr &PAL) {
680 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
681 printSimpleType(Out, Ty, isSigned, NameSoFar);
685 // Check to see if the type is named.
686 if (!IgnoreName || isa<OpaqueType>(Ty)) {
687 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
688 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
691 switch (Ty->getTypeID()) {
692 case Type::FunctionTyID: {
693 const FunctionType *FTy = cast<FunctionType>(Ty);
694 std::stringstream FunctionInnards;
695 FunctionInnards << " (" << NameSoFar << ") (";
697 for (FunctionType::param_iterator I = FTy->param_begin(),
698 E = FTy->param_end(); I != E; ++I) {
699 const Type *ArgTy = *I;
700 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
701 assert(isa<PointerType>(ArgTy));
702 ArgTy = cast<PointerType>(ArgTy)->getElementType();
704 if (I != FTy->param_begin())
705 FunctionInnards << ", ";
706 printType(FunctionInnards, ArgTy,
707 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
710 if (FTy->isVarArg()) {
711 if (FTy->getNumParams())
712 FunctionInnards << ", ...";
713 } else if (!FTy->getNumParams()) {
714 FunctionInnards << "void";
716 FunctionInnards << ')';
717 std::string tstr = FunctionInnards.str();
718 printType(Out, FTy->getReturnType(),
719 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
722 case Type::StructTyID: {
723 const StructType *STy = cast<StructType>(Ty);
724 Out << NameSoFar + " {\n";
726 for (StructType::element_iterator I = STy->element_begin(),
727 E = STy->element_end(); I != E; ++I) {
729 printType(Out, *I, false, "field" + utostr(Idx++));
734 Out << " __attribute__ ((packed))";
738 case Type::PointerTyID: {
739 const PointerType *PTy = cast<PointerType>(Ty);
740 std::string ptrName = "*" + NameSoFar;
742 if (isa<ArrayType>(PTy->getElementType()) ||
743 isa<VectorType>(PTy->getElementType()))
744 ptrName = "(" + ptrName + ")";
747 // Must be a function ptr cast!
748 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
749 return printType(Out, PTy->getElementType(), false, ptrName);
752 case Type::ArrayTyID: {
753 const ArrayType *ATy = cast<ArrayType>(Ty);
754 unsigned NumElements = ATy->getNumElements();
755 if (NumElements == 0) NumElements = 1;
756 // Arrays are wrapped in structs to allow them to have normal
757 // value semantics (avoiding the array "decay").
758 Out << NameSoFar << " { ";
759 printType(Out, ATy->getElementType(), false,
760 "array[" + utostr(NumElements) + "]");
764 case Type::OpaqueTyID: {
765 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
766 assert(TypeNames.find(Ty) == TypeNames.end());
767 TypeNames[Ty] = TyName;
768 return Out << TyName << ' ' << NameSoFar;
771 llvm_unreachable("Unhandled case in getTypeProps!");
777 void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
779 // As a special case, print the array as a string if it is an array of
780 // ubytes or an array of sbytes with positive values.
782 const Type *ETy = CPA->getType()->getElementType();
783 bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty);
785 // Make sure the last character is a null char, as automatically added by C
786 if (isString && (CPA->getNumOperands() == 0 ||
787 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
792 // Keep track of whether the last number was a hexadecimal escape
793 bool LastWasHex = false;
795 // Do not include the last character, which we know is null
796 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
797 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
799 // Print it out literally if it is a printable character. The only thing
800 // to be careful about is when the last letter output was a hex escape
801 // code, in which case we have to be careful not to print out hex digits
802 // explicitly (the C compiler thinks it is a continuation of the previous
803 // character, sheesh...)
805 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
807 if (C == '"' || C == '\\')
808 Out << "\\" << (char)C;
814 case '\n': Out << "\\n"; break;
815 case '\t': Out << "\\t"; break;
816 case '\r': Out << "\\r"; break;
817 case '\v': Out << "\\v"; break;
818 case '\a': Out << "\\a"; break;
819 case '\"': Out << "\\\""; break;
820 case '\'': Out << "\\\'"; break;
823 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
824 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
833 if (CPA->getNumOperands()) {
835 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
836 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
838 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
845 void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
847 if (CP->getNumOperands()) {
849 printConstant(cast<Constant>(CP->getOperand(0)), Static);
850 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
852 printConstant(cast<Constant>(CP->getOperand(i)), Static);
858 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
859 // textually as a double (rather than as a reference to a stack-allocated
860 // variable). We decide this by converting CFP to a string and back into a
861 // double, and then checking whether the conversion results in a bit-equal
862 // double to the original value of CFP. This depends on us and the target C
863 // compiler agreeing on the conversion process (which is pretty likely since we
864 // only deal in IEEE FP).
866 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
868 // Do long doubles in hex for now.
869 if (CFP->getType() != Type::FloatTy && CFP->getType() != Type::DoubleTy)
871 APFloat APF = APFloat(CFP->getValueAPF()); // copy
872 if (CFP->getType() == Type::FloatTy)
873 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
874 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
876 sprintf(Buffer, "%a", APF.convertToDouble());
877 if (!strncmp(Buffer, "0x", 2) ||
878 !strncmp(Buffer, "-0x", 3) ||
879 !strncmp(Buffer, "+0x", 3))
880 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
883 std::string StrVal = ftostr(APF);
885 while (StrVal[0] == ' ')
886 StrVal.erase(StrVal.begin());
888 // Check to make sure that the stringized number is not some string like "Inf"
889 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
890 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
891 ((StrVal[0] == '-' || StrVal[0] == '+') &&
892 (StrVal[1] >= '0' && StrVal[1] <= '9')))
893 // Reparse stringized version!
894 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
899 /// Print out the casting for a cast operation. This does the double casting
900 /// necessary for conversion to the destination type, if necessary.
901 /// @brief Print a cast
902 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
903 // Print the destination type cast
905 case Instruction::UIToFP:
906 case Instruction::SIToFP:
907 case Instruction::IntToPtr:
908 case Instruction::Trunc:
909 case Instruction::BitCast:
910 case Instruction::FPExt:
911 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
913 printType(Out, DstTy);
916 case Instruction::ZExt:
917 case Instruction::PtrToInt:
918 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
920 printSimpleType(Out, DstTy, false);
923 case Instruction::SExt:
924 case Instruction::FPToSI: // For these, make sure we get a signed dest
926 printSimpleType(Out, DstTy, true);
930 llvm_unreachable("Invalid cast opcode");
933 // Print the source type cast
935 case Instruction::UIToFP:
936 case Instruction::ZExt:
938 printSimpleType(Out, SrcTy, false);
941 case Instruction::SIToFP:
942 case Instruction::SExt:
944 printSimpleType(Out, SrcTy, true);
947 case Instruction::IntToPtr:
948 case Instruction::PtrToInt:
949 // Avoid "cast to pointer from integer of different size" warnings
950 Out << "(unsigned long)";
952 case Instruction::Trunc:
953 case Instruction::BitCast:
954 case Instruction::FPExt:
955 case Instruction::FPTrunc:
956 case Instruction::FPToSI:
957 case Instruction::FPToUI:
958 break; // These don't need a source cast.
960 llvm_unreachable("Invalid cast opcode");
965 // printConstant - The LLVM Constant to C Constant converter.
966 void CWriter::printConstant(Constant *CPV, bool Static) {
967 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
968 switch (CE->getOpcode()) {
969 case Instruction::Trunc:
970 case Instruction::ZExt:
971 case Instruction::SExt:
972 case Instruction::FPTrunc:
973 case Instruction::FPExt:
974 case Instruction::UIToFP:
975 case Instruction::SIToFP:
976 case Instruction::FPToUI:
977 case Instruction::FPToSI:
978 case Instruction::PtrToInt:
979 case Instruction::IntToPtr:
980 case Instruction::BitCast:
982 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
983 if (CE->getOpcode() == Instruction::SExt &&
984 CE->getOperand(0)->getType() == Type::Int1Ty) {
985 // Make sure we really sext from bool here by subtracting from 0
988 printConstant(CE->getOperand(0), Static);
989 if (CE->getType() == Type::Int1Ty &&
990 (CE->getOpcode() == Instruction::Trunc ||
991 CE->getOpcode() == Instruction::FPToUI ||
992 CE->getOpcode() == Instruction::FPToSI ||
993 CE->getOpcode() == Instruction::PtrToInt)) {
994 // Make sure we really truncate to bool here by anding with 1
1000 case Instruction::GetElementPtr:
1002 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
1003 gep_type_end(CPV), Static);
1006 case Instruction::Select:
1008 printConstant(CE->getOperand(0), Static);
1010 printConstant(CE->getOperand(1), Static);
1012 printConstant(CE->getOperand(2), Static);
1015 case Instruction::Add:
1016 case Instruction::FAdd:
1017 case Instruction::Sub:
1018 case Instruction::FSub:
1019 case Instruction::Mul:
1020 case Instruction::FMul:
1021 case Instruction::SDiv:
1022 case Instruction::UDiv:
1023 case Instruction::FDiv:
1024 case Instruction::URem:
1025 case Instruction::SRem:
1026 case Instruction::FRem:
1027 case Instruction::And:
1028 case Instruction::Or:
1029 case Instruction::Xor:
1030 case Instruction::ICmp:
1031 case Instruction::Shl:
1032 case Instruction::LShr:
1033 case Instruction::AShr:
1036 bool NeedsClosingParens = printConstExprCast(CE, Static);
1037 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1038 switch (CE->getOpcode()) {
1039 case Instruction::Add:
1040 case Instruction::FAdd: Out << " + "; break;
1041 case Instruction::Sub:
1042 case Instruction::FSub: Out << " - "; break;
1043 case Instruction::Mul:
1044 case Instruction::FMul: Out << " * "; break;
1045 case Instruction::URem:
1046 case Instruction::SRem:
1047 case Instruction::FRem: Out << " % "; break;
1048 case Instruction::UDiv:
1049 case Instruction::SDiv:
1050 case Instruction::FDiv: Out << " / "; break;
1051 case Instruction::And: Out << " & "; break;
1052 case Instruction::Or: Out << " | "; break;
1053 case Instruction::Xor: Out << " ^ "; break;
1054 case Instruction::Shl: Out << " << "; break;
1055 case Instruction::LShr:
1056 case Instruction::AShr: Out << " >> "; break;
1057 case Instruction::ICmp:
1058 switch (CE->getPredicate()) {
1059 case ICmpInst::ICMP_EQ: Out << " == "; break;
1060 case ICmpInst::ICMP_NE: Out << " != "; break;
1061 case ICmpInst::ICMP_SLT:
1062 case ICmpInst::ICMP_ULT: Out << " < "; break;
1063 case ICmpInst::ICMP_SLE:
1064 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1065 case ICmpInst::ICMP_SGT:
1066 case ICmpInst::ICMP_UGT: Out << " > "; break;
1067 case ICmpInst::ICMP_SGE:
1068 case ICmpInst::ICMP_UGE: Out << " >= "; break;
1069 default: llvm_unreachable("Illegal ICmp predicate");
1072 default: llvm_unreachable("Illegal opcode here!");
1074 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1075 if (NeedsClosingParens)
1080 case Instruction::FCmp: {
1082 bool NeedsClosingParens = printConstExprCast(CE, Static);
1083 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1085 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1089 switch (CE->getPredicate()) {
1090 default: llvm_unreachable("Illegal FCmp predicate");
1091 case FCmpInst::FCMP_ORD: op = "ord"; break;
1092 case FCmpInst::FCMP_UNO: op = "uno"; break;
1093 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1094 case FCmpInst::FCMP_UNE: op = "une"; break;
1095 case FCmpInst::FCMP_ULT: op = "ult"; break;
1096 case FCmpInst::FCMP_ULE: op = "ule"; break;
1097 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1098 case FCmpInst::FCMP_UGE: op = "uge"; break;
1099 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1100 case FCmpInst::FCMP_ONE: op = "one"; break;
1101 case FCmpInst::FCMP_OLT: op = "olt"; break;
1102 case FCmpInst::FCMP_OLE: op = "ole"; break;
1103 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1104 case FCmpInst::FCMP_OGE: op = "oge"; break;
1106 Out << "llvm_fcmp_" << op << "(";
1107 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1109 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1112 if (NeedsClosingParens)
1119 cerr << "CWriter Error: Unhandled constant expression: "
1122 llvm_unreachable(0);
1124 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
1126 printType(Out, CPV->getType()); // sign doesn't matter
1127 Out << ")/*UNDEF*/";
1128 if (!isa<VectorType>(CPV->getType())) {
1136 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1137 const Type* Ty = CI->getType();
1138 if (Ty == Type::Int1Ty)
1139 Out << (CI->getZExtValue() ? '1' : '0');
1140 else if (Ty == Type::Int32Ty)
1141 Out << CI->getZExtValue() << 'u';
1142 else if (Ty->getPrimitiveSizeInBits() > 32)
1143 Out << CI->getZExtValue() << "ull";
1146 printSimpleType(Out, Ty, false) << ')';
1147 if (CI->isMinValue(true))
1148 Out << CI->getZExtValue() << 'u';
1150 Out << CI->getSExtValue();
1156 switch (CPV->getType()->getTypeID()) {
1157 case Type::FloatTyID:
1158 case Type::DoubleTyID:
1159 case Type::X86_FP80TyID:
1160 case Type::PPC_FP128TyID:
1161 case Type::FP128TyID: {
1162 ConstantFP *FPC = cast<ConstantFP>(CPV);
1163 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
1164 if (I != FPConstantMap.end()) {
1165 // Because of FP precision problems we must load from a stack allocated
1166 // value that holds the value in hex.
1167 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" :
1168 FPC->getType() == Type::DoubleTy ? "double" :
1170 << "*)&FPConstant" << I->second << ')';
1173 if (FPC->getType() == Type::FloatTy)
1174 V = FPC->getValueAPF().convertToFloat();
1175 else if (FPC->getType() == Type::DoubleTy)
1176 V = FPC->getValueAPF().convertToDouble();
1178 // Long double. Convert the number to double, discarding precision.
1179 // This is not awesome, but it at least makes the CBE output somewhat
1181 APFloat Tmp = FPC->getValueAPF();
1183 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1184 V = Tmp.convertToDouble();
1190 // FIXME the actual NaN bits should be emitted.
1191 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1193 const unsigned long QuietNaN = 0x7ff8UL;
1194 //const unsigned long SignalNaN = 0x7ff4UL;
1196 // We need to grab the first part of the FP #
1199 uint64_t ll = DoubleToBits(V);
1200 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
1202 std::string Num(&Buffer[0], &Buffer[6]);
1203 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1205 if (FPC->getType() == Type::FloatTy)
1206 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1207 << Buffer << "\") /*nan*/ ";
1209 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1210 << Buffer << "\") /*nan*/ ";
1211 } else if (IsInf(V)) {
1213 if (V < 0) Out << '-';
1214 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
1218 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1219 // Print out the constant as a floating point number.
1221 sprintf(Buffer, "%a", V);
1224 Num = ftostr(FPC->getValueAPF());
1232 case Type::ArrayTyID:
1233 // Use C99 compound expression literal initializer syntax.
1236 printType(Out, CPV->getType());
1239 Out << "{ "; // Arrays are wrapped in struct types.
1240 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
1241 printConstantArray(CA, Static);
1243 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1244 const ArrayType *AT = cast<ArrayType>(CPV->getType());
1246 if (AT->getNumElements()) {
1248 Constant *CZ = Context->getNullValue(AT->getElementType());
1249 printConstant(CZ, Static);
1250 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1252 printConstant(CZ, Static);
1257 Out << " }"; // Arrays are wrapped in struct types.
1260 case Type::VectorTyID:
1261 // Use C99 compound expression literal initializer syntax.
1264 printType(Out, CPV->getType());
1267 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
1268 printConstantVector(CV, Static);
1270 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1271 const VectorType *VT = cast<VectorType>(CPV->getType());
1273 Constant *CZ = Context->getNullValue(VT->getElementType());
1274 printConstant(CZ, Static);
1275 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
1277 printConstant(CZ, Static);
1283 case Type::StructTyID:
1284 // Use C99 compound expression literal initializer syntax.
1287 printType(Out, CPV->getType());
1290 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1291 const StructType *ST = cast<StructType>(CPV->getType());
1293 if (ST->getNumElements()) {
1295 printConstant(Context->getNullValue(ST->getElementType(0)), Static);
1296 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1298 printConstant(Context->getNullValue(ST->getElementType(i)), Static);
1304 if (CPV->getNumOperands()) {
1306 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
1307 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1309 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
1316 case Type::PointerTyID:
1317 if (isa<ConstantPointerNull>(CPV)) {
1319 printType(Out, CPV->getType()); // sign doesn't matter
1320 Out << ")/*NULL*/0)";
1322 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1323 writeOperand(GV, Static);
1329 cerr << "Unknown constant type: " << *CPV << "\n";
1331 llvm_unreachable(0);
1335 // Some constant expressions need to be casted back to the original types
1336 // because their operands were casted to the expected type. This function takes
1337 // care of detecting that case and printing the cast for the ConstantExpr.
1338 bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
1339 bool NeedsExplicitCast = false;
1340 const Type *Ty = CE->getOperand(0)->getType();
1341 bool TypeIsSigned = false;
1342 switch (CE->getOpcode()) {
1343 case Instruction::Add:
1344 case Instruction::Sub:
1345 case Instruction::Mul:
1346 // We need to cast integer arithmetic so that it is always performed
1347 // as unsigned, to avoid undefined behavior on overflow.
1348 case Instruction::LShr:
1349 case Instruction::URem:
1350 case Instruction::UDiv: NeedsExplicitCast = true; break;
1351 case Instruction::AShr:
1352 case Instruction::SRem:
1353 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1354 case Instruction::SExt:
1356 NeedsExplicitCast = true;
1357 TypeIsSigned = true;
1359 case Instruction::ZExt:
1360 case Instruction::Trunc:
1361 case Instruction::FPTrunc:
1362 case Instruction::FPExt:
1363 case Instruction::UIToFP:
1364 case Instruction::SIToFP:
1365 case Instruction::FPToUI:
1366 case Instruction::FPToSI:
1367 case Instruction::PtrToInt:
1368 case Instruction::IntToPtr:
1369 case Instruction::BitCast:
1371 NeedsExplicitCast = true;
1375 if (NeedsExplicitCast) {
1377 if (Ty->isInteger() && Ty != Type::Int1Ty)
1378 printSimpleType(Out, Ty, TypeIsSigned);
1380 printType(Out, Ty); // not integer, sign doesn't matter
1383 return NeedsExplicitCast;
1386 // Print a constant assuming that it is the operand for a given Opcode. The
1387 // opcodes that care about sign need to cast their operands to the expected
1388 // type before the operation proceeds. This function does the casting.
1389 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1391 // Extract the operand's type, we'll need it.
1392 const Type* OpTy = CPV->getType();
1394 // Indicate whether to do the cast or not.
1395 bool shouldCast = false;
1396 bool typeIsSigned = false;
1398 // Based on the Opcode for which this Constant is being written, determine
1399 // the new type to which the operand should be casted by setting the value
1400 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1404 // for most instructions, it doesn't matter
1406 case Instruction::Add:
1407 case Instruction::Sub:
1408 case Instruction::Mul:
1409 // We need to cast integer arithmetic so that it is always performed
1410 // as unsigned, to avoid undefined behavior on overflow.
1411 case Instruction::LShr:
1412 case Instruction::UDiv:
1413 case Instruction::URem:
1416 case Instruction::AShr:
1417 case Instruction::SDiv:
1418 case Instruction::SRem:
1420 typeIsSigned = true;
1424 // Write out the casted constant if we should, otherwise just write the
1428 printSimpleType(Out, OpTy, typeIsSigned);
1430 printConstant(CPV, false);
1433 printConstant(CPV, false);
1436 std::string CWriter::GetValueName(const Value *Operand) {
1437 // Mangle globals with the standard mangler interface for LLC compatibility.
1438 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand))
1439 return Mang->getMangledName(GV);
1441 std::string Name = Operand->getName();
1443 if (Name.empty()) { // Assign unique names to local temporaries.
1444 unsigned &No = AnonValueNumbers[Operand];
1446 No = ++NextAnonValueNumber;
1447 Name = "tmp__" + utostr(No);
1450 std::string VarName;
1451 VarName.reserve(Name.capacity());
1453 for (std::string::iterator I = Name.begin(), E = Name.end();
1457 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1458 (ch >= '0' && ch <= '9') || ch == '_')) {
1460 sprintf(buffer, "_%x_", ch);
1466 return "llvm_cbe_" + VarName;
1469 /// writeInstComputationInline - Emit the computation for the specified
1470 /// instruction inline, with no destination provided.
1471 void CWriter::writeInstComputationInline(Instruction &I) {
1472 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1474 const Type *Ty = I.getType();
1475 if (Ty->isInteger() && (Ty!=Type::Int1Ty && Ty!=Type::Int8Ty &&
1476 Ty!=Type::Int16Ty && Ty!=Type::Int32Ty && Ty!=Type::Int64Ty)) {
1477 llvm_report_error("The C backend does not currently support integer "
1478 "types of widths other than 1, 8, 16, 32, 64.\n"
1479 "This is being tracked as PR 4158.");
1482 // If this is a non-trivial bool computation, make sure to truncate down to
1483 // a 1 bit value. This is important because we want "add i1 x, y" to return
1484 // "0" when x and y are true, not "2" for example.
1485 bool NeedBoolTrunc = false;
1486 if (I.getType() == Type::Int1Ty && !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
1487 NeedBoolTrunc = true;
1499 void CWriter::writeOperandInternal(Value *Operand, bool Static) {
1500 if (Instruction *I = dyn_cast<Instruction>(Operand))
1501 // Should we inline this instruction to build a tree?
1502 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1504 writeInstComputationInline(*I);
1509 Constant* CPV = dyn_cast<Constant>(Operand);
1511 if (CPV && !isa<GlobalValue>(CPV))
1512 printConstant(CPV, Static);
1514 Out << GetValueName(Operand);
1517 void CWriter::writeOperand(Value *Operand, bool Static) {
1518 bool isAddressImplicit = isAddressExposed(Operand);
1519 if (isAddressImplicit)
1520 Out << "(&"; // Global variables are referenced as their addresses by llvm
1522 writeOperandInternal(Operand, Static);
1524 if (isAddressImplicit)
1528 // Some instructions need to have their result value casted back to the
1529 // original types because their operands were casted to the expected type.
1530 // This function takes care of detecting that case and printing the cast
1531 // for the Instruction.
1532 bool CWriter::writeInstructionCast(const Instruction &I) {
1533 const Type *Ty = I.getOperand(0)->getType();
1534 switch (I.getOpcode()) {
1535 case Instruction::Add:
1536 case Instruction::Sub:
1537 case Instruction::Mul:
1538 // We need to cast integer arithmetic so that it is always performed
1539 // as unsigned, to avoid undefined behavior on overflow.
1540 case Instruction::LShr:
1541 case Instruction::URem:
1542 case Instruction::UDiv:
1544 printSimpleType(Out, Ty, false);
1547 case Instruction::AShr:
1548 case Instruction::SRem:
1549 case Instruction::SDiv:
1551 printSimpleType(Out, Ty, true);
1559 // Write the operand with a cast to another type based on the Opcode being used.
1560 // This will be used in cases where an instruction has specific type
1561 // requirements (usually signedness) for its operands.
1562 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1564 // Extract the operand's type, we'll need it.
1565 const Type* OpTy = Operand->getType();
1567 // Indicate whether to do the cast or not.
1568 bool shouldCast = false;
1570 // Indicate whether the cast should be to a signed type or not.
1571 bool castIsSigned = false;
1573 // Based on the Opcode for which this Operand is being written, determine
1574 // the new type to which the operand should be casted by setting the value
1575 // of OpTy. If we change OpTy, also set shouldCast to true.
1578 // for most instructions, it doesn't matter
1580 case Instruction::Add:
1581 case Instruction::Sub:
1582 case Instruction::Mul:
1583 // We need to cast integer arithmetic so that it is always performed
1584 // as unsigned, to avoid undefined behavior on overflow.
1585 case Instruction::LShr:
1586 case Instruction::UDiv:
1587 case Instruction::URem: // Cast to unsigned first
1589 castIsSigned = false;
1591 case Instruction::GetElementPtr:
1592 case Instruction::AShr:
1593 case Instruction::SDiv:
1594 case Instruction::SRem: // Cast to signed first
1596 castIsSigned = true;
1600 // Write out the casted operand if we should, otherwise just write the
1604 printSimpleType(Out, OpTy, castIsSigned);
1606 writeOperand(Operand);
1609 writeOperand(Operand);
1612 // Write the operand with a cast to another type based on the icmp predicate
1614 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1615 // This has to do a cast to ensure the operand has the right signedness.
1616 // Also, if the operand is a pointer, we make sure to cast to an integer when
1617 // doing the comparison both for signedness and so that the C compiler doesn't
1618 // optimize things like "p < NULL" to false (p may contain an integer value
1620 bool shouldCast = Cmp.isRelational();
1622 // Write out the casted operand if we should, otherwise just write the
1625 writeOperand(Operand);
1629 // Should this be a signed comparison? If so, convert to signed.
1630 bool castIsSigned = Cmp.isSignedPredicate();
1632 // If the operand was a pointer, convert to a large integer type.
1633 const Type* OpTy = Operand->getType();
1634 if (isa<PointerType>(OpTy))
1635 OpTy = TD->getIntPtrType();
1638 printSimpleType(Out, OpTy, castIsSigned);
1640 writeOperand(Operand);
1644 // generateCompilerSpecificCode - This is where we add conditional compilation
1645 // directives to cater to specific compilers as need be.
1647 static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
1648 const TargetData *TD) {
1649 // Alloca is hard to get, and we don't want to include stdlib.h here.
1650 Out << "/* get a declaration for alloca */\n"
1651 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1652 << "#define alloca(x) __builtin_alloca((x))\n"
1653 << "#define _alloca(x) __builtin_alloca((x))\n"
1654 << "#elif defined(__APPLE__)\n"
1655 << "extern void *__builtin_alloca(unsigned long);\n"
1656 << "#define alloca(x) __builtin_alloca(x)\n"
1657 << "#define longjmp _longjmp\n"
1658 << "#define setjmp _setjmp\n"
1659 << "#elif defined(__sun__)\n"
1660 << "#if defined(__sparcv9)\n"
1661 << "extern void *__builtin_alloca(unsigned long);\n"
1663 << "extern void *__builtin_alloca(unsigned int);\n"
1665 << "#define alloca(x) __builtin_alloca(x)\n"
1666 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)\n"
1667 << "#define alloca(x) __builtin_alloca(x)\n"
1668 << "#elif defined(_MSC_VER)\n"
1669 << "#define inline _inline\n"
1670 << "#define alloca(x) _alloca(x)\n"
1672 << "#include <alloca.h>\n"
1675 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1676 // If we aren't being compiled with GCC, just drop these attributes.
1677 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1678 << "#define __attribute__(X)\n"
1681 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1682 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1683 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1684 << "#elif defined(__GNUC__)\n"
1685 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1687 << "#define __EXTERNAL_WEAK__\n"
1690 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1691 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1692 << "#define __ATTRIBUTE_WEAK__\n"
1693 << "#elif defined(__GNUC__)\n"
1694 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1696 << "#define __ATTRIBUTE_WEAK__\n"
1699 // Add hidden visibility support. FIXME: APPLE_CC?
1700 Out << "#if defined(__GNUC__)\n"
1701 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1704 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1705 // From the GCC documentation:
1707 // double __builtin_nan (const char *str)
1709 // This is an implementation of the ISO C99 function nan.
1711 // Since ISO C99 defines this function in terms of strtod, which we do
1712 // not implement, a description of the parsing is in order. The string is
1713 // parsed as by strtol; that is, the base is recognized by leading 0 or
1714 // 0x prefixes. The number parsed is placed in the significand such that
1715 // the least significant bit of the number is at the least significant
1716 // bit of the significand. The number is truncated to fit the significand
1717 // field provided. The significand is forced to be a quiet NaN.
1719 // This function, if given a string literal, is evaluated early enough
1720 // that it is considered a compile-time constant.
1722 // float __builtin_nanf (const char *str)
1724 // Similar to __builtin_nan, except the return type is float.
1726 // double __builtin_inf (void)
1728 // Similar to __builtin_huge_val, except a warning is generated if the
1729 // target floating-point format does not support infinities. This
1730 // function is suitable for implementing the ISO C99 macro INFINITY.
1732 // float __builtin_inff (void)
1734 // Similar to __builtin_inf, except the return type is float.
1735 Out << "#ifdef __GNUC__\n"
1736 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1737 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1738 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1739 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1740 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1741 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1742 << "#define LLVM_PREFETCH(addr,rw,locality) "
1743 "__builtin_prefetch(addr,rw,locality)\n"
1744 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1745 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1746 << "#define LLVM_ASM __asm__\n"
1748 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1749 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1750 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1751 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1752 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1753 << "#define LLVM_INFF 0.0F /* Float */\n"
1754 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1755 << "#define __ATTRIBUTE_CTOR__\n"
1756 << "#define __ATTRIBUTE_DTOR__\n"
1757 << "#define LLVM_ASM(X)\n"
1760 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1761 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1762 << "#define __builtin_stack_restore(X) /* noop */\n"
1765 // Output typedefs for 128-bit integers. If these are needed with a
1766 // 32-bit target or with a C compiler that doesn't support mode(TI),
1767 // more drastic measures will be needed.
1768 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1769 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1770 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1773 // Output target-specific code that should be inserted into main.
1774 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1777 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1778 /// the StaticTors set.
1779 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1780 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1781 if (!InitList) return;
1783 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1784 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1785 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1787 if (CS->getOperand(1)->isNullValue())
1788 return; // Found a null terminator, exit printing.
1789 Constant *FP = CS->getOperand(1);
1790 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1792 FP = CE->getOperand(0);
1793 if (Function *F = dyn_cast<Function>(FP))
1794 StaticTors.insert(F);
1798 enum SpecialGlobalClass {
1800 GlobalCtors, GlobalDtors,
1804 /// getGlobalVariableClass - If this is a global that is specially recognized
1805 /// by LLVM, return a code that indicates how we should handle it.
1806 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1807 // If this is a global ctors/dtors list, handle it now.
1808 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1809 if (GV->getName() == "llvm.global_ctors")
1811 else if (GV->getName() == "llvm.global_dtors")
1815 // Otherwise, it it is other metadata, don't print it. This catches things
1816 // like debug information.
1817 if (GV->getSection() == "llvm.metadata")
1824 bool CWriter::doInitialization(Module &M) {
1828 TD = new TargetData(&M);
1829 IL = new IntrinsicLowering(*TD);
1830 IL->AddPrototypes(M);
1832 // Ensure that all structure types have names...
1833 Mang = new Mangler(M);
1834 Mang->markCharUnacceptable('.');
1836 // Keep track of which functions are static ctors/dtors so they can have
1837 // an attribute added to their prototypes.
1838 std::set<Function*> StaticCtors, StaticDtors;
1839 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1841 switch (getGlobalVariableClass(I)) {
1844 FindStaticTors(I, StaticCtors);
1847 FindStaticTors(I, StaticDtors);
1852 // get declaration for alloca
1853 Out << "/* Provide Declarations */\n";
1854 Out << "#include <stdarg.h>\n"; // Varargs support
1855 Out << "#include <setjmp.h>\n"; // Unwind support
1856 generateCompilerSpecificCode(Out, TD);
1858 // Provide a definition for `bool' if not compiling with a C++ compiler.
1860 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1862 << "\n\n/* Support for floating point constants */\n"
1863 << "typedef unsigned long long ConstantDoubleTy;\n"
1864 << "typedef unsigned int ConstantFloatTy;\n"
1865 << "typedef struct { unsigned long long f1; unsigned short f2; "
1866 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1867 // This is used for both kinds of 128-bit long double; meaning differs.
1868 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1869 " ConstantFP128Ty;\n"
1870 << "\n\n/* Global Declarations */\n";
1872 // First output all the declarations for the program, because C requires
1873 // Functions & globals to be declared before they are used.
1876 // Loop over the symbol table, emitting all named constants...
1877 printModuleTypes(M.getTypeSymbolTable());
1879 // Global variable declarations...
1880 if (!M.global_empty()) {
1881 Out << "\n/* External Global Variable Declarations */\n";
1882 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1885 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1886 I->hasCommonLinkage())
1888 else if (I->hasDLLImportLinkage())
1889 Out << "__declspec(dllimport) ";
1891 continue; // Internal Global
1893 // Thread Local Storage
1894 if (I->isThreadLocal())
1897 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1899 if (I->hasExternalWeakLinkage())
1900 Out << " __EXTERNAL_WEAK__";
1905 // Function declarations
1906 Out << "\n/* Function Declarations */\n";
1907 Out << "double fmod(double, double);\n"; // Support for FP rem
1908 Out << "float fmodf(float, float);\n";
1909 Out << "long double fmodl(long double, long double);\n";
1911 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1912 // Don't print declarations for intrinsic functions.
1913 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
1914 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1915 if (I->hasExternalWeakLinkage())
1917 printFunctionSignature(I, true);
1918 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1919 Out << " __ATTRIBUTE_WEAK__";
1920 if (I->hasExternalWeakLinkage())
1921 Out << " __EXTERNAL_WEAK__";
1922 if (StaticCtors.count(I))
1923 Out << " __ATTRIBUTE_CTOR__";
1924 if (StaticDtors.count(I))
1925 Out << " __ATTRIBUTE_DTOR__";
1926 if (I->hasHiddenVisibility())
1927 Out << " __HIDDEN__";
1929 if (I->hasName() && I->getName()[0] == 1)
1930 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1936 // Output the global variable declarations
1937 if (!M.global_empty()) {
1938 Out << "\n\n/* Global Variable Declarations */\n";
1939 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1941 if (!I->isDeclaration()) {
1942 // Ignore special globals, such as debug info.
1943 if (getGlobalVariableClass(I))
1946 if (I->hasLocalLinkage())
1951 // Thread Local Storage
1952 if (I->isThreadLocal())
1955 printType(Out, I->getType()->getElementType(), false,
1958 if (I->hasLinkOnceLinkage())
1959 Out << " __attribute__((common))";
1960 else if (I->hasCommonLinkage()) // FIXME is this right?
1961 Out << " __ATTRIBUTE_WEAK__";
1962 else if (I->hasWeakLinkage())
1963 Out << " __ATTRIBUTE_WEAK__";
1964 else if (I->hasExternalWeakLinkage())
1965 Out << " __EXTERNAL_WEAK__";
1966 if (I->hasHiddenVisibility())
1967 Out << " __HIDDEN__";
1972 // Output the global variable definitions and contents...
1973 if (!M.global_empty()) {
1974 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1975 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1977 if (!I->isDeclaration()) {
1978 // Ignore special globals, such as debug info.
1979 if (getGlobalVariableClass(I))
1982 if (I->hasLocalLinkage())
1984 else if (I->hasDLLImportLinkage())
1985 Out << "__declspec(dllimport) ";
1986 else if (I->hasDLLExportLinkage())
1987 Out << "__declspec(dllexport) ";
1989 // Thread Local Storage
1990 if (I->isThreadLocal())
1993 printType(Out, I->getType()->getElementType(), false,
1995 if (I->hasLinkOnceLinkage())
1996 Out << " __attribute__((common))";
1997 else if (I->hasWeakLinkage())
1998 Out << " __ATTRIBUTE_WEAK__";
1999 else if (I->hasCommonLinkage())
2000 Out << " __ATTRIBUTE_WEAK__";
2002 if (I->hasHiddenVisibility())
2003 Out << " __HIDDEN__";
2005 // If the initializer is not null, emit the initializer. If it is null,
2006 // we try to avoid emitting large amounts of zeros. The problem with
2007 // this, however, occurs when the variable has weak linkage. In this
2008 // case, the assembler will complain about the variable being both weak
2009 // and common, so we disable this optimization.
2010 // FIXME common linkage should avoid this problem.
2011 if (!I->getInitializer()->isNullValue()) {
2013 writeOperand(I->getInitializer(), true);
2014 } else if (I->hasWeakLinkage()) {
2015 // We have to specify an initializer, but it doesn't have to be
2016 // complete. If the value is an aggregate, print out { 0 }, and let
2017 // the compiler figure out the rest of the zeros.
2019 if (isa<StructType>(I->getInitializer()->getType()) ||
2020 isa<VectorType>(I->getInitializer()->getType())) {
2022 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
2023 // As with structs and vectors, but with an extra set of braces
2024 // because arrays are wrapped in structs.
2027 // Just print it out normally.
2028 writeOperand(I->getInitializer(), true);
2036 Out << "\n\n/* Function Bodies */\n";
2038 // Emit some helper functions for dealing with FCMP instruction's
2040 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2041 Out << "return X == X && Y == Y; }\n";
2042 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2043 Out << "return X != X || Y != Y; }\n";
2044 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
2045 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
2046 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
2047 Out << "return X != Y; }\n";
2048 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
2049 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
2050 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
2051 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
2052 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
2053 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
2054 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
2055 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
2056 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
2057 Out << "return X == Y ; }\n";
2058 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
2059 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
2060 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
2061 Out << "return X < Y ; }\n";
2062 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
2063 Out << "return X > Y ; }\n";
2064 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
2065 Out << "return X <= Y ; }\n";
2066 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
2067 Out << "return X >= Y ; }\n";
2072 /// Output all floating point constants that cannot be printed accurately...
2073 void CWriter::printFloatingPointConstants(Function &F) {
2074 // Scan the module for floating point constants. If any FP constant is used
2075 // in the function, we want to redirect it here so that we do not depend on
2076 // the precision of the printed form, unless the printed form preserves
2079 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2081 printFloatingPointConstants(*I);
2086 void CWriter::printFloatingPointConstants(const Constant *C) {
2087 // If this is a constant expression, recursively check for constant fp values.
2088 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2089 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2090 printFloatingPointConstants(CE->getOperand(i));
2094 // Otherwise, check for a FP constant that we need to print.
2095 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2097 // Do not put in FPConstantMap if safe.
2098 isFPCSafeToPrint(FPC) ||
2099 // Already printed this constant?
2100 FPConstantMap.count(FPC))
2103 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2105 if (FPC->getType() == Type::DoubleTy) {
2106 double Val = FPC->getValueAPF().convertToDouble();
2107 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2108 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2109 << " = 0x" << utohexstr(i)
2110 << "ULL; /* " << Val << " */\n";
2111 } else if (FPC->getType() == Type::FloatTy) {
2112 float Val = FPC->getValueAPF().convertToFloat();
2113 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2115 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2116 << " = 0x" << utohexstr(i)
2117 << "U; /* " << Val << " */\n";
2118 } else if (FPC->getType() == Type::X86_FP80Ty) {
2119 // api needed to prevent premature destruction
2120 APInt api = FPC->getValueAPF().bitcastToAPInt();
2121 const uint64_t *p = api.getRawData();
2122 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
2123 << " = { 0x" << utohexstr(p[0])
2124 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
2125 << "}; /* Long double constant */\n";
2126 } else if (FPC->getType() == Type::PPC_FP128Ty) {
2127 APInt api = FPC->getValueAPF().bitcastToAPInt();
2128 const uint64_t *p = api.getRawData();
2129 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2131 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2132 << "}; /* Long double constant */\n";
2135 llvm_unreachable("Unknown float type!");
2141 /// printSymbolTable - Run through symbol table looking for type names. If a
2142 /// type name is found, emit its declaration...
2144 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
2145 Out << "/* Helper union for bitcasts */\n";
2146 Out << "typedef union {\n";
2147 Out << " unsigned int Int32;\n";
2148 Out << " unsigned long long Int64;\n";
2149 Out << " float Float;\n";
2150 Out << " double Double;\n";
2151 Out << "} llvmBitCastUnion;\n";
2153 // We are only interested in the type plane of the symbol table.
2154 TypeSymbolTable::const_iterator I = TST.begin();
2155 TypeSymbolTable::const_iterator End = TST.end();
2157 // If there are no type names, exit early.
2158 if (I == End) return;
2160 // Print out forward declarations for structure types before anything else!
2161 Out << "/* Structure forward decls */\n";
2162 for (; I != End; ++I) {
2163 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
2164 Out << Name << ";\n";
2165 TypeNames.insert(std::make_pair(I->second, Name));
2170 // Now we can print out typedefs. Above, we guaranteed that this can only be
2171 // for struct or opaque types.
2172 Out << "/* Typedefs */\n";
2173 for (I = TST.begin(); I != End; ++I) {
2174 std::string Name = "l_" + Mang->makeNameProper(I->first);
2176 printType(Out, I->second, false, Name);
2182 // Keep track of which structures have been printed so far...
2183 std::set<const Type *> StructPrinted;
2185 // Loop over all structures then push them into the stack so they are
2186 // printed in the correct order.
2188 Out << "/* Structure contents */\n";
2189 for (I = TST.begin(); I != End; ++I)
2190 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
2191 // Only print out used types!
2192 printContainedStructs(I->second, StructPrinted);
2195 // Push the struct onto the stack and recursively push all structs
2196 // this one depends on.
2198 // TODO: Make this work properly with vector types
2200 void CWriter::printContainedStructs(const Type *Ty,
2201 std::set<const Type*> &StructPrinted) {
2202 // Don't walk through pointers.
2203 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
2205 // Print all contained types first.
2206 for (Type::subtype_iterator I = Ty->subtype_begin(),
2207 E = Ty->subtype_end(); I != E; ++I)
2208 printContainedStructs(*I, StructPrinted);
2210 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
2211 // Check to see if we have already printed this struct.
2212 if (StructPrinted.insert(Ty).second) {
2213 // Print structure type out.
2214 std::string Name = TypeNames[Ty];
2215 printType(Out, Ty, false, Name, true);
2221 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
2222 /// isStructReturn - Should this function actually return a struct by-value?
2223 bool isStructReturn = F->hasStructRetAttr();
2225 if (F->hasLocalLinkage()) Out << "static ";
2226 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2227 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
2228 switch (F->getCallingConv()) {
2229 case CallingConv::X86_StdCall:
2230 Out << "__attribute__((stdcall)) ";
2232 case CallingConv::X86_FastCall:
2233 Out << "__attribute__((fastcall)) ";
2237 // Loop over the arguments, printing them...
2238 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
2239 const AttrListPtr &PAL = F->getAttributes();
2241 std::stringstream FunctionInnards;
2243 // Print out the name...
2244 FunctionInnards << GetValueName(F) << '(';
2246 bool PrintedArg = false;
2247 if (!F->isDeclaration()) {
2248 if (!F->arg_empty()) {
2249 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2252 // If this is a struct-return function, don't print the hidden
2253 // struct-return argument.
2254 if (isStructReturn) {
2255 assert(I != E && "Invalid struct return function!");
2260 std::string ArgName;
2261 for (; I != E; ++I) {
2262 if (PrintedArg) FunctionInnards << ", ";
2263 if (I->hasName() || !Prototype)
2264 ArgName = GetValueName(I);
2267 const Type *ArgTy = I->getType();
2268 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2269 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2270 ByValParams.insert(I);
2272 printType(FunctionInnards, ArgTy,
2273 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
2280 // Loop over the arguments, printing them.
2281 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
2284 // If this is a struct-return function, don't print the hidden
2285 // struct-return argument.
2286 if (isStructReturn) {
2287 assert(I != E && "Invalid struct return function!");
2292 for (; I != E; ++I) {
2293 if (PrintedArg) FunctionInnards << ", ";
2294 const Type *ArgTy = *I;
2295 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2296 assert(isa<PointerType>(ArgTy));
2297 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2299 printType(FunctionInnards, ArgTy,
2300 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
2306 // Finish printing arguments... if this is a vararg function, print the ...,
2307 // unless there are no known types, in which case, we just emit ().
2309 if (FT->isVarArg() && PrintedArg) {
2310 if (PrintedArg) FunctionInnards << ", ";
2311 FunctionInnards << "..."; // Output varargs portion of signature!
2312 } else if (!FT->isVarArg() && !PrintedArg) {
2313 FunctionInnards << "void"; // ret() -> ret(void) in C.
2315 FunctionInnards << ')';
2317 // Get the return tpe for the function.
2319 if (!isStructReturn)
2320 RetTy = F->getReturnType();
2322 // If this is a struct-return function, print the struct-return type.
2323 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2326 // Print out the return type and the signature built above.
2327 printType(Out, RetTy,
2328 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
2329 FunctionInnards.str());
2332 static inline bool isFPIntBitCast(const Instruction &I) {
2333 if (!isa<BitCastInst>(I))
2335 const Type *SrcTy = I.getOperand(0)->getType();
2336 const Type *DstTy = I.getType();
2337 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2338 (DstTy->isFloatingPoint() && SrcTy->isInteger());
2341 void CWriter::printFunction(Function &F) {
2342 /// isStructReturn - Should this function actually return a struct by-value?
2343 bool isStructReturn = F.hasStructRetAttr();
2345 printFunctionSignature(&F, false);
2348 // If this is a struct return function, handle the result with magic.
2349 if (isStructReturn) {
2350 const Type *StructTy =
2351 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2353 printType(Out, StructTy, false, "StructReturn");
2354 Out << "; /* Struct return temporary */\n";
2357 printType(Out, F.arg_begin()->getType(), false,
2358 GetValueName(F.arg_begin()));
2359 Out << " = &StructReturn;\n";
2362 bool PrintedVar = false;
2364 // print local variable information for the function
2365 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2366 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2368 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2369 Out << "; /* Address-exposed local */\n";
2371 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
2373 printType(Out, I->getType(), false, GetValueName(&*I));
2376 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2378 printType(Out, I->getType(), false,
2379 GetValueName(&*I)+"__PHI_TEMPORARY");
2384 // We need a temporary for the BitCast to use so it can pluck a value out
2385 // of a union to do the BitCast. This is separate from the need for a
2386 // variable to hold the result of the BitCast.
2387 if (isFPIntBitCast(*I)) {
2388 Out << " llvmBitCastUnion " << GetValueName(&*I)
2389 << "__BITCAST_TEMPORARY;\n";
2397 if (F.hasExternalLinkage() && F.getName() == "main")
2398 Out << " CODE_FOR_MAIN();\n";
2400 // print the basic blocks
2401 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2402 if (Loop *L = LI->getLoopFor(BB)) {
2403 if (L->getHeader() == BB && L->getParentLoop() == 0)
2406 printBasicBlock(BB);
2413 void CWriter::printLoop(Loop *L) {
2414 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2415 << "' to make GCC happy */\n";
2416 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2417 BasicBlock *BB = L->getBlocks()[i];
2418 Loop *BBLoop = LI->getLoopFor(BB);
2420 printBasicBlock(BB);
2421 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2424 Out << " } while (1); /* end of syntactic loop '"
2425 << L->getHeader()->getName() << "' */\n";
2428 void CWriter::printBasicBlock(BasicBlock *BB) {
2430 // Don't print the label for the basic block if there are no uses, or if
2431 // the only terminator use is the predecessor basic block's terminator.
2432 // We have to scan the use list because PHI nodes use basic blocks too but
2433 // do not require a label to be generated.
2435 bool NeedsLabel = false;
2436 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2437 if (isGotoCodeNecessary(*PI, BB)) {
2442 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2444 // Output all of the instructions in the basic block...
2445 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2447 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2448 if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
2452 writeInstComputationInline(*II);
2457 // Don't emit prefix or suffix for the terminator.
2458 visit(*BB->getTerminator());
2462 // Specific Instruction type classes... note that all of the casts are
2463 // necessary because we use the instruction classes as opaque types...
2465 void CWriter::visitReturnInst(ReturnInst &I) {
2466 // If this is a struct return function, return the temporary struct.
2467 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
2469 if (isStructReturn) {
2470 Out << " return StructReturn;\n";
2474 // Don't output a void return if this is the last basic block in the function
2475 if (I.getNumOperands() == 0 &&
2476 &*--I.getParent()->getParent()->end() == I.getParent() &&
2477 !I.getParent()->size() == 1) {
2481 if (I.getNumOperands() > 1) {
2484 printType(Out, I.getParent()->getParent()->getReturnType());
2485 Out << " llvm_cbe_mrv_temp = {\n";
2486 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2488 writeOperand(I.getOperand(i));
2494 Out << " return llvm_cbe_mrv_temp;\n";
2500 if (I.getNumOperands()) {
2502 writeOperand(I.getOperand(0));
2507 void CWriter::visitSwitchInst(SwitchInst &SI) {
2510 writeOperand(SI.getOperand(0));
2511 Out << ") {\n default:\n";
2512 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2513 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2515 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2517 writeOperand(SI.getOperand(i));
2519 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2520 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2521 printBranchToBlock(SI.getParent(), Succ, 2);
2522 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
2528 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2529 Out << " /*UNREACHABLE*/;\n";
2532 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2533 /// FIXME: This should be reenabled, but loop reordering safe!!
2536 if (next(Function::iterator(From)) != Function::iterator(To))
2537 return true; // Not the direct successor, we need a goto.
2539 //isa<SwitchInst>(From->getTerminator())
2541 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2546 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2547 BasicBlock *Successor,
2549 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2550 PHINode *PN = cast<PHINode>(I);
2551 // Now we have to do the printing.
2552 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2553 if (!isa<UndefValue>(IV)) {
2554 Out << std::string(Indent, ' ');
2555 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2557 Out << "; /* for PHI node */\n";
2562 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2564 if (isGotoCodeNecessary(CurBB, Succ)) {
2565 Out << std::string(Indent, ' ') << " goto ";
2571 // Branch instruction printing - Avoid printing out a branch to a basic block
2572 // that immediately succeeds the current one.
2574 void CWriter::visitBranchInst(BranchInst &I) {
2576 if (I.isConditional()) {
2577 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2579 writeOperand(I.getCondition());
2582 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2583 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2585 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2586 Out << " } else {\n";
2587 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2588 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2591 // First goto not necessary, assume second one is...
2593 writeOperand(I.getCondition());
2596 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2597 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2602 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2603 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2608 // PHI nodes get copied into temporary values at the end of predecessor basic
2609 // blocks. We now need to copy these temporary values into the REAL value for
2611 void CWriter::visitPHINode(PHINode &I) {
2613 Out << "__PHI_TEMPORARY";
2617 void CWriter::visitBinaryOperator(Instruction &I) {
2618 // binary instructions, shift instructions, setCond instructions.
2619 assert(!isa<PointerType>(I.getType()));
2621 // We must cast the results of binary operations which might be promoted.
2622 bool needsCast = false;
2623 if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty)
2624 || (I.getType() == Type::FloatTy)) {
2627 printType(Out, I.getType(), false);
2631 // If this is a negation operation, print it out as such. For FP, we don't
2632 // want to print "-0.0 - X".
2633 if (BinaryOperator::isNeg(&I)) {
2635 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2637 } else if (BinaryOperator::isFNeg(&I)) {
2639 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2641 } else if (I.getOpcode() == Instruction::FRem) {
2642 // Output a call to fmod/fmodf instead of emitting a%b
2643 if (I.getType() == Type::FloatTy)
2645 else if (I.getType() == Type::DoubleTy)
2647 else // all 3 flavors of long double
2649 writeOperand(I.getOperand(0));
2651 writeOperand(I.getOperand(1));
2655 // Write out the cast of the instruction's value back to the proper type
2657 bool NeedsClosingParens = writeInstructionCast(I);
2659 // Certain instructions require the operand to be forced to a specific type
2660 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2661 // below for operand 1
2662 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2664 switch (I.getOpcode()) {
2665 case Instruction::Add:
2666 case Instruction::FAdd: Out << " + "; break;
2667 case Instruction::Sub:
2668 case Instruction::FSub: Out << " - "; break;
2669 case Instruction::Mul:
2670 case Instruction::FMul: Out << " * "; break;
2671 case Instruction::URem:
2672 case Instruction::SRem:
2673 case Instruction::FRem: Out << " % "; break;
2674 case Instruction::UDiv:
2675 case Instruction::SDiv:
2676 case Instruction::FDiv: Out << " / "; break;
2677 case Instruction::And: Out << " & "; break;
2678 case Instruction::Or: Out << " | "; break;
2679 case Instruction::Xor: Out << " ^ "; break;
2680 case Instruction::Shl : Out << " << "; break;
2681 case Instruction::LShr:
2682 case Instruction::AShr: Out << " >> "; break;
2685 cerr << "Invalid operator type!" << I;
2687 llvm_unreachable(0);
2690 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2691 if (NeedsClosingParens)
2700 void CWriter::visitICmpInst(ICmpInst &I) {
2701 // We must cast the results of icmp which might be promoted.
2702 bool needsCast = false;
2704 // Write out the cast of the instruction's value back to the proper type
2706 bool NeedsClosingParens = writeInstructionCast(I);
2708 // Certain icmp predicate require the operand to be forced to a specific type
2709 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2710 // below for operand 1
2711 writeOperandWithCast(I.getOperand(0), I);
2713 switch (I.getPredicate()) {
2714 case ICmpInst::ICMP_EQ: Out << " == "; break;
2715 case ICmpInst::ICMP_NE: Out << " != "; break;
2716 case ICmpInst::ICMP_ULE:
2717 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2718 case ICmpInst::ICMP_UGE:
2719 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2720 case ICmpInst::ICMP_ULT:
2721 case ICmpInst::ICMP_SLT: Out << " < "; break;
2722 case ICmpInst::ICMP_UGT:
2723 case ICmpInst::ICMP_SGT: Out << " > "; break;
2726 cerr << "Invalid icmp predicate!" << I;
2728 llvm_unreachable(0);
2731 writeOperandWithCast(I.getOperand(1), I);
2732 if (NeedsClosingParens)
2740 void CWriter::visitFCmpInst(FCmpInst &I) {
2741 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2745 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2751 switch (I.getPredicate()) {
2752 default: llvm_unreachable("Illegal FCmp predicate");
2753 case FCmpInst::FCMP_ORD: op = "ord"; break;
2754 case FCmpInst::FCMP_UNO: op = "uno"; break;
2755 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2756 case FCmpInst::FCMP_UNE: op = "une"; break;
2757 case FCmpInst::FCMP_ULT: op = "ult"; break;
2758 case FCmpInst::FCMP_ULE: op = "ule"; break;
2759 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2760 case FCmpInst::FCMP_UGE: op = "uge"; break;
2761 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2762 case FCmpInst::FCMP_ONE: op = "one"; break;
2763 case FCmpInst::FCMP_OLT: op = "olt"; break;
2764 case FCmpInst::FCMP_OLE: op = "ole"; break;
2765 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2766 case FCmpInst::FCMP_OGE: op = "oge"; break;
2769 Out << "llvm_fcmp_" << op << "(";
2770 // Write the first operand
2771 writeOperand(I.getOperand(0));
2773 // Write the second operand
2774 writeOperand(I.getOperand(1));
2778 static const char * getFloatBitCastField(const Type *Ty) {
2779 switch (Ty->getTypeID()) {
2780 default: llvm_unreachable("Invalid Type");
2781 case Type::FloatTyID: return "Float";
2782 case Type::DoubleTyID: return "Double";
2783 case Type::IntegerTyID: {
2784 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2793 void CWriter::visitCastInst(CastInst &I) {
2794 const Type *DstTy = I.getType();
2795 const Type *SrcTy = I.getOperand(0)->getType();
2796 if (isFPIntBitCast(I)) {
2798 // These int<->float and long<->double casts need to be handled specially
2799 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2800 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2801 writeOperand(I.getOperand(0));
2802 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2803 << getFloatBitCastField(I.getType());
2809 printCast(I.getOpcode(), SrcTy, DstTy);
2811 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
2812 if (SrcTy == Type::Int1Ty && I.getOpcode() == Instruction::SExt)
2815 writeOperand(I.getOperand(0));
2817 if (DstTy == Type::Int1Ty &&
2818 (I.getOpcode() == Instruction::Trunc ||
2819 I.getOpcode() == Instruction::FPToUI ||
2820 I.getOpcode() == Instruction::FPToSI ||
2821 I.getOpcode() == Instruction::PtrToInt)) {
2822 // Make sure we really get a trunc to bool by anding the operand with 1
2828 void CWriter::visitSelectInst(SelectInst &I) {
2830 writeOperand(I.getCondition());
2832 writeOperand(I.getTrueValue());
2834 writeOperand(I.getFalseValue());
2839 void CWriter::lowerIntrinsics(Function &F) {
2840 // This is used to keep track of intrinsics that get generated to a lowered
2841 // function. We must generate the prototypes before the function body which
2842 // will only be expanded on first use (by the loop below).
2843 std::vector<Function*> prototypesToGen;
2845 // Examine all the instructions in this function to find the intrinsics that
2846 // need to be lowered.
2847 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2848 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2849 if (CallInst *CI = dyn_cast<CallInst>(I++))
2850 if (Function *F = CI->getCalledFunction())
2851 switch (F->getIntrinsicID()) {
2852 case Intrinsic::not_intrinsic:
2853 case Intrinsic::memory_barrier:
2854 case Intrinsic::vastart:
2855 case Intrinsic::vacopy:
2856 case Intrinsic::vaend:
2857 case Intrinsic::returnaddress:
2858 case Intrinsic::frameaddress:
2859 case Intrinsic::setjmp:
2860 case Intrinsic::longjmp:
2861 case Intrinsic::prefetch:
2862 case Intrinsic::dbg_stoppoint:
2863 case Intrinsic::powi:
2864 case Intrinsic::x86_sse_cmp_ss:
2865 case Intrinsic::x86_sse_cmp_ps:
2866 case Intrinsic::x86_sse2_cmp_sd:
2867 case Intrinsic::x86_sse2_cmp_pd:
2868 case Intrinsic::ppc_altivec_lvsl:
2869 // We directly implement these intrinsics
2872 // If this is an intrinsic that directly corresponds to a GCC
2873 // builtin, we handle it.
2874 const char *BuiltinName = "";
2875 #define GET_GCC_BUILTIN_NAME
2876 #include "llvm/Intrinsics.gen"
2877 #undef GET_GCC_BUILTIN_NAME
2878 // If we handle it, don't lower it.
2879 if (BuiltinName[0]) break;
2881 // All other intrinsic calls we must lower.
2882 Instruction *Before = 0;
2883 if (CI != &BB->front())
2884 Before = prior(BasicBlock::iterator(CI));
2886 IL->LowerIntrinsicCall(CI);
2887 if (Before) { // Move iterator to instruction after call
2892 // If the intrinsic got lowered to another call, and that call has
2893 // a definition then we need to make sure its prototype is emitted
2894 // before any calls to it.
2895 if (CallInst *Call = dyn_cast<CallInst>(I))
2896 if (Function *NewF = Call->getCalledFunction())
2897 if (!NewF->isDeclaration())
2898 prototypesToGen.push_back(NewF);
2903 // We may have collected some prototypes to emit in the loop above.
2904 // Emit them now, before the function that uses them is emitted. But,
2905 // be careful not to emit them twice.
2906 std::vector<Function*>::iterator I = prototypesToGen.begin();
2907 std::vector<Function*>::iterator E = prototypesToGen.end();
2908 for ( ; I != E; ++I) {
2909 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2911 printFunctionSignature(*I, true);
2917 void CWriter::visitCallInst(CallInst &I) {
2918 if (isa<InlineAsm>(I.getOperand(0)))
2919 return visitInlineAsm(I);
2921 bool WroteCallee = false;
2923 // Handle intrinsic function calls first...
2924 if (Function *F = I.getCalledFunction())
2925 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2926 if (visitBuiltinCall(I, ID, WroteCallee))
2929 Value *Callee = I.getCalledValue();
2931 const PointerType *PTy = cast<PointerType>(Callee->getType());
2932 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2934 // If this is a call to a struct-return function, assign to the first
2935 // parameter instead of passing it to the call.
2936 const AttrListPtr &PAL = I.getAttributes();
2937 bool hasByVal = I.hasByValArgument();
2938 bool isStructRet = I.hasStructRetAttr();
2940 writeOperandDeref(I.getOperand(1));
2944 if (I.isTailCall()) Out << " /*tail*/ ";
2947 // If this is an indirect call to a struct return function, we need to cast
2948 // the pointer. Ditto for indirect calls with byval arguments.
2949 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
2951 // GCC is a real PITA. It does not permit codegening casts of functions to
2952 // function pointers if they are in a call (it generates a trap instruction
2953 // instead!). We work around this by inserting a cast to void* in between
2954 // the function and the function pointer cast. Unfortunately, we can't just
2955 // form the constant expression here, because the folder will immediately
2958 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2959 // that void* and function pointers have the same size. :( To deal with this
2960 // in the common case, we handle casts where the number of arguments passed
2963 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2965 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2971 // Ok, just cast the pointer type.
2974 printStructReturnPointerFunctionType(Out, PAL,
2975 cast<PointerType>(I.getCalledValue()->getType()));
2977 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
2979 printType(Out, I.getCalledValue()->getType());
2982 writeOperand(Callee);
2983 if (NeedsCast) Out << ')';
2988 unsigned NumDeclaredParams = FTy->getNumParams();
2990 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2992 if (isStructRet) { // Skip struct return argument.
2997 bool PrintedArg = false;
2998 for (; AI != AE; ++AI, ++ArgNo) {
2999 if (PrintedArg) Out << ", ";
3000 if (ArgNo < NumDeclaredParams &&
3001 (*AI)->getType() != FTy->getParamType(ArgNo)) {
3003 printType(Out, FTy->getParamType(ArgNo),
3004 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
3007 // Check if the argument is expected to be passed by value.
3008 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
3009 writeOperandDeref(*AI);
3017 /// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3018 /// if the entire call is handled, return false it it wasn't handled, and
3019 /// optionally set 'WroteCallee' if the callee has already been printed out.
3020 bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3021 bool &WroteCallee) {
3024 // If this is an intrinsic that directly corresponds to a GCC
3025 // builtin, we emit it here.
3026 const char *BuiltinName = "";
3027 Function *F = I.getCalledFunction();
3028 #define GET_GCC_BUILTIN_NAME
3029 #include "llvm/Intrinsics.gen"
3030 #undef GET_GCC_BUILTIN_NAME
3031 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3037 case Intrinsic::memory_barrier:
3038 Out << "__sync_synchronize()";
3040 case Intrinsic::vastart:
3043 Out << "va_start(*(va_list*)";
3044 writeOperand(I.getOperand(1));
3046 // Output the last argument to the enclosing function.
3047 if (I.getParent()->getParent()->arg_empty()) {
3049 raw_string_ostream Msg(msg);
3050 Msg << "The C backend does not currently support zero "
3051 << "argument varargs functions, such as '"
3052 << I.getParent()->getParent()->getName() << "'!";
3053 llvm_report_error(Msg.str());
3055 writeOperand(--I.getParent()->getParent()->arg_end());
3058 case Intrinsic::vaend:
3059 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3060 Out << "0; va_end(*(va_list*)";
3061 writeOperand(I.getOperand(1));
3064 Out << "va_end(*(va_list*)0)";
3067 case Intrinsic::vacopy:
3069 Out << "va_copy(*(va_list*)";
3070 writeOperand(I.getOperand(1));
3071 Out << ", *(va_list*)";
3072 writeOperand(I.getOperand(2));
3075 case Intrinsic::returnaddress:
3076 Out << "__builtin_return_address(";
3077 writeOperand(I.getOperand(1));
3080 case Intrinsic::frameaddress:
3081 Out << "__builtin_frame_address(";
3082 writeOperand(I.getOperand(1));
3085 case Intrinsic::powi:
3086 Out << "__builtin_powi(";
3087 writeOperand(I.getOperand(1));
3089 writeOperand(I.getOperand(2));
3092 case Intrinsic::setjmp:
3093 Out << "setjmp(*(jmp_buf*)";
3094 writeOperand(I.getOperand(1));
3097 case Intrinsic::longjmp:
3098 Out << "longjmp(*(jmp_buf*)";
3099 writeOperand(I.getOperand(1));
3101 writeOperand(I.getOperand(2));
3104 case Intrinsic::prefetch:
3105 Out << "LLVM_PREFETCH((const void *)";
3106 writeOperand(I.getOperand(1));
3108 writeOperand(I.getOperand(2));
3110 writeOperand(I.getOperand(3));
3113 case Intrinsic::stacksave:
3114 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3115 // to work around GCC bugs (see PR1809).
3116 Out << "0; *((void**)&" << GetValueName(&I)
3117 << ") = __builtin_stack_save()";
3119 case Intrinsic::dbg_stoppoint: {
3120 // If we use writeOperand directly we get a "u" suffix which is rejected
3122 std::stringstream SPIStr;
3123 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3124 SPI.getDirectory()->print(SPIStr);
3128 Out << SPIStr.str();
3130 SPI.getFileName()->print(SPIStr);
3131 Out << SPIStr.str() << "\"\n";
3134 case Intrinsic::x86_sse_cmp_ss:
3135 case Intrinsic::x86_sse_cmp_ps:
3136 case Intrinsic::x86_sse2_cmp_sd:
3137 case Intrinsic::x86_sse2_cmp_pd:
3139 printType(Out, I.getType());
3141 // Multiple GCC builtins multiplex onto this intrinsic.
3142 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
3143 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
3144 case 0: Out << "__builtin_ia32_cmpeq"; break;
3145 case 1: Out << "__builtin_ia32_cmplt"; break;
3146 case 2: Out << "__builtin_ia32_cmple"; break;
3147 case 3: Out << "__builtin_ia32_cmpunord"; break;
3148 case 4: Out << "__builtin_ia32_cmpneq"; break;
3149 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3150 case 6: Out << "__builtin_ia32_cmpnle"; break;
3151 case 7: Out << "__builtin_ia32_cmpord"; break;
3153 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3157 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3163 writeOperand(I.getOperand(1));
3165 writeOperand(I.getOperand(2));
3168 case Intrinsic::ppc_altivec_lvsl:
3170 printType(Out, I.getType());
3172 Out << "__builtin_altivec_lvsl(0, (void*)";
3173 writeOperand(I.getOperand(1));
3179 //This converts the llvm constraint string to something gcc is expecting.
3180 //TODO: work out platform independent constraints and factor those out
3181 // of the per target tables
3182 // handle multiple constraint codes
3183 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
3185 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3187 const char *const *table = 0;
3189 //Grab the translation table from TargetAsmInfo if it exists
3192 const TargetMachineRegistry::entry* Match =
3193 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
3195 //Per platform Target Machines don't exist, so create it
3196 // this must be done only once
3197 const TargetMachine* TM = Match->CtorFn(*TheModule, "");
3198 TAsm = TM->getTargetAsmInfo();
3202 table = TAsm->getAsmCBE();
3204 //Search the translation table if it exists
3205 for (int i = 0; table && table[i]; i += 2)
3206 if (c.Codes[0] == table[i])
3209 //default is identity
3213 //TODO: import logic from AsmPrinter.cpp
3214 static std::string gccifyAsm(std::string asmstr) {
3215 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3216 if (asmstr[i] == '\n')
3217 asmstr.replace(i, 1, "\\n");
3218 else if (asmstr[i] == '\t')
3219 asmstr.replace(i, 1, "\\t");
3220 else if (asmstr[i] == '$') {
3221 if (asmstr[i + 1] == '{') {
3222 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3223 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3224 std::string n = "%" +
3225 asmstr.substr(a + 1, b - a - 1) +
3226 asmstr.substr(i + 2, a - i - 2);
3227 asmstr.replace(i, b - i + 1, n);
3230 asmstr.replace(i, 1, "%");
3232 else if (asmstr[i] == '%')//grr
3233 { asmstr.replace(i, 1, "%%"); ++i;}
3238 //TODO: assumptions about what consume arguments from the call are likely wrong
3239 // handle communitivity
3240 void CWriter::visitInlineAsm(CallInst &CI) {
3241 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
3242 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
3244 std::vector<std::pair<Value*, int> > ResultVals;
3245 if (CI.getType() == Type::VoidTy)
3247 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3248 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3249 ResultVals.push_back(std::make_pair(&CI, (int)i));
3251 ResultVals.push_back(std::make_pair(&CI, -1));
3254 // Fix up the asm string for gcc and emit it.
3255 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3258 unsigned ValueCount = 0;
3259 bool IsFirst = true;
3261 // Convert over all the output constraints.
3262 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3263 E = Constraints.end(); I != E; ++I) {
3265 if (I->Type != InlineAsm::isOutput) {
3267 continue; // Ignore non-output constraints.
3270 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3271 std::string C = InterpretASMConstraint(*I);
3272 if (C.empty()) continue;
3283 if (ValueCount < ResultVals.size()) {
3284 DestVal = ResultVals[ValueCount].first;
3285 DestValNo = ResultVals[ValueCount].second;
3287 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3289 if (I->isEarlyClobber)
3292 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3293 if (DestValNo != -1)
3294 Out << ".field" << DestValNo; // Multiple retvals.
3300 // Convert over all the input constraints.
3304 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3305 E = Constraints.end(); I != E; ++I) {
3306 if (I->Type != InlineAsm::isInput) {
3308 continue; // Ignore non-input constraints.
3311 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3312 std::string C = InterpretASMConstraint(*I);
3313 if (C.empty()) continue;
3320 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3321 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3323 Out << "\"" << C << "\"(";
3325 writeOperand(SrcVal);
3327 writeOperandDeref(SrcVal);
3331 // Convert over the clobber constraints.
3334 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3335 E = Constraints.end(); I != E; ++I) {
3336 if (I->Type != InlineAsm::isClobber)
3337 continue; // Ignore non-input constraints.
3339 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3340 std::string C = InterpretASMConstraint(*I);
3341 if (C.empty()) continue;
3348 Out << '\"' << C << '"';
3354 void CWriter::visitMallocInst(MallocInst &I) {
3355 llvm_unreachable("lowerallocations pass didn't work!");
3358 void CWriter::visitAllocaInst(AllocaInst &I) {
3360 printType(Out, I.getType());
3361 Out << ") alloca(sizeof(";
3362 printType(Out, I.getType()->getElementType());
3364 if (I.isArrayAllocation()) {
3366 writeOperand(I.getOperand(0));
3371 void CWriter::visitFreeInst(FreeInst &I) {
3372 llvm_unreachable("lowerallocations pass didn't work!");
3375 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
3376 gep_type_iterator E, bool Static) {
3378 // If there are no indices, just print out the pointer.
3384 // Find out if the last index is into a vector. If so, we have to print this
3385 // specially. Since vectors can't have elements of indexable type, only the
3386 // last index could possibly be of a vector element.
3387 const VectorType *LastIndexIsVector = 0;
3389 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3390 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
3395 // If the last index is into a vector, we can't print it as &a[i][j] because
3396 // we can't index into a vector with j in GCC. Instead, emit this as
3397 // (((float*)&a[i])+j)
3398 if (LastIndexIsVector) {
3400 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3406 // If the first index is 0 (very typical) we can do a number of
3407 // simplifications to clean up the code.
3408 Value *FirstOp = I.getOperand();
3409 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3410 // First index isn't simple, print it the hard way.
3413 ++I; // Skip the zero index.
3415 // Okay, emit the first operand. If Ptr is something that is already address
3416 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3417 if (isAddressExposed(Ptr)) {
3418 writeOperandInternal(Ptr, Static);
3419 } else if (I != E && isa<StructType>(*I)) {
3420 // If we didn't already emit the first operand, see if we can print it as
3421 // P->f instead of "P[0].f"
3423 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3424 ++I; // eat the struct index as well.
3426 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3433 for (; I != E; ++I) {
3434 if (isa<StructType>(*I)) {
3435 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3436 } else if (isa<ArrayType>(*I)) {
3438 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3440 } else if (!isa<VectorType>(*I)) {
3442 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3445 // If the last index is into a vector, then print it out as "+j)". This
3446 // works with the 'LastIndexIsVector' code above.
3447 if (isa<Constant>(I.getOperand()) &&
3448 cast<Constant>(I.getOperand())->isNullValue()) {
3449 Out << "))"; // avoid "+0".
3452 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3460 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3461 bool IsVolatile, unsigned Alignment) {
3463 bool IsUnaligned = Alignment &&
3464 Alignment < TD->getABITypeAlignment(OperandType);
3468 if (IsVolatile || IsUnaligned) {
3471 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3472 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3475 if (IsVolatile) Out << "volatile ";
3481 writeOperand(Operand);
3483 if (IsVolatile || IsUnaligned) {
3490 void CWriter::visitLoadInst(LoadInst &I) {
3491 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3496 void CWriter::visitStoreInst(StoreInst &I) {
3497 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3498 I.isVolatile(), I.getAlignment());
3500 Value *Operand = I.getOperand(0);
3501 Constant *BitMask = 0;
3502 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3503 if (!ITy->isPowerOf2ByteWidth())
3504 // We have a bit width that doesn't match an even power-of-2 byte
3505 // size. Consequently we must & the value with the type's bit mask
3506 BitMask = Context->getConstantInt(ITy, ITy->getBitMask());
3509 writeOperand(Operand);
3512 printConstant(BitMask, false);
3517 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
3518 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
3519 gep_type_end(I), false);
3522 void CWriter::visitVAArgInst(VAArgInst &I) {
3523 Out << "va_arg(*(va_list*)";
3524 writeOperand(I.getOperand(0));
3526 printType(Out, I.getType());
3530 void CWriter::visitInsertElementInst(InsertElementInst &I) {
3531 const Type *EltTy = I.getType()->getElementType();
3532 writeOperand(I.getOperand(0));
3535 printType(Out, PointerType::getUnqual(EltTy));
3536 Out << ")(&" << GetValueName(&I) << "))[";
3537 writeOperand(I.getOperand(2));
3539 writeOperand(I.getOperand(1));
3543 void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3544 // We know that our operand is not inlined.
3547 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3548 printType(Out, PointerType::getUnqual(EltTy));
3549 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3550 writeOperand(I.getOperand(1));
3554 void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3556 printType(Out, SVI.getType());
3558 const VectorType *VT = SVI.getType();
3559 unsigned NumElts = VT->getNumElements();
3560 const Type *EltTy = VT->getElementType();
3562 for (unsigned i = 0; i != NumElts; ++i) {
3564 int SrcVal = SVI.getMaskValue(i);
3565 if ((unsigned)SrcVal >= NumElts*2) {
3566 Out << " 0/*undef*/ ";
3568 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3569 if (isa<Instruction>(Op)) {
3570 // Do an extractelement of this value from the appropriate input.
3572 printType(Out, PointerType::getUnqual(EltTy));
3573 Out << ")(&" << GetValueName(Op)
3574 << "))[" << (SrcVal & (NumElts-1)) << "]";
3575 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3578 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
3587 void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3588 // Start by copying the entire aggregate value into the result variable.
3589 writeOperand(IVI.getOperand(0));
3592 // Then do the insert to update the field.
3593 Out << GetValueName(&IVI);
3594 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3596 const Type *IndexedTy =
3597 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3598 if (isa<ArrayType>(IndexedTy))
3599 Out << ".array[" << *i << "]";
3601 Out << ".field" << *i;
3604 writeOperand(IVI.getOperand(1));
3607 void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3609 if (isa<UndefValue>(EVI.getOperand(0))) {
3611 printType(Out, EVI.getType());
3612 Out << ") 0/*UNDEF*/";
3614 Out << GetValueName(EVI.getOperand(0));
3615 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3617 const Type *IndexedTy =
3618 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3619 if (isa<ArrayType>(IndexedTy))
3620 Out << ".array[" << *i << "]";
3622 Out << ".field" << *i;
3628 //===----------------------------------------------------------------------===//
3629 // External Interface declaration
3630 //===----------------------------------------------------------------------===//
3632 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
3633 formatted_raw_ostream &o,
3634 CodeGenFileType FileType,
3635 CodeGenOpt::Level OptLevel) {
3636 if (FileType != TargetMachine::AssemblyFile) return true;
3638 PM.add(createGCLoweringPass());
3639 PM.add(createLowerAllocationsPass(true));
3640 PM.add(createLowerInvokePass());
3641 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3642 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3643 PM.add(new CWriter(o));
3644 PM.add(createGCInfoDeleter());