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 extern Target TheCBackendTarget;
62 static RegisterTarget<CTargetMachine> X(TheCBackendTarget, "c", "C backend");
64 // Force static initialization.
65 extern "C" void LLVMInitializeCBackendTarget() { }
68 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
69 /// any unnamed structure types that are used by the program, and merges
70 /// external functions with the same name.
72 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
75 CBackendNameAllUsedStructsAndMergeFunctions()
77 void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequired<FindUsedTypes>();
81 virtual const char *getPassName() const {
82 return "C backend type canonicalizer";
85 virtual bool runOnModule(Module &M);
88 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
90 /// CWriter - This class is the main chunk of code that converts an LLVM
91 /// module to a C translation unit.
92 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
93 formatted_raw_ostream &Out;
94 IntrinsicLowering *IL;
97 const Module *TheModule;
98 const TargetAsmInfo* TAsm;
100 std::map<const Type *, std::string> TypeNames;
101 std::map<const ConstantFP *, unsigned> FPConstantMap;
102 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
103 std::set<const Argument*> ByValParams;
105 unsigned OpaqueCounter;
106 DenseMap<const Value*, unsigned> AnonValueNumbers;
107 unsigned NextAnonValueNumber;
111 explicit CWriter(formatted_raw_ostream &o)
112 : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0),
113 TheModule(0), TAsm(0), TD(0), OpaqueCounter(0), NextAnonValueNumber(0) {
117 virtual const char *getPassName() const { return "C backend"; }
119 void getAnalysisUsage(AnalysisUsage &AU) const {
120 AU.addRequired<LoopInfo>();
121 AU.setPreservesAll();
124 virtual bool doInitialization(Module &M);
126 bool runOnFunction(Function &F) {
127 // Do not codegen any 'available_externally' functions at all, they have
128 // definitions outside the translation unit.
129 if (F.hasAvailableExternallyLinkage())
132 LI = &getAnalysis<LoopInfo>();
134 // Get rid of intrinsics we can't handle.
137 // Output all floating point constants that cannot be printed accurately.
138 printFloatingPointConstants(F);
144 virtual bool doFinalization(Module &M) {
149 FPConstantMap.clear();
152 intrinsicPrototypesAlreadyGenerated.clear();
156 raw_ostream &printType(formatted_raw_ostream &Out,
158 bool isSigned = false,
159 const std::string &VariableName = "",
160 bool IgnoreName = false,
161 const AttrListPtr &PAL = AttrListPtr());
162 std::ostream &printType(std::ostream &Out, const Type *Ty,
163 bool isSigned = false,
164 const std::string &VariableName = "",
165 bool IgnoreName = false,
166 const AttrListPtr &PAL = AttrListPtr());
167 raw_ostream &printSimpleType(formatted_raw_ostream &Out,
170 const std::string &NameSoFar = "");
171 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
173 const std::string &NameSoFar = "");
175 void printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
176 const AttrListPtr &PAL,
177 const PointerType *Ty);
179 /// writeOperandDeref - Print the result of dereferencing the specified
180 /// operand with '*'. This is equivalent to printing '*' then using
181 /// writeOperand, but avoids excess syntax in some cases.
182 void writeOperandDeref(Value *Operand) {
183 if (isAddressExposed(Operand)) {
184 // Already something with an address exposed.
185 writeOperandInternal(Operand);
188 writeOperand(Operand);
193 void writeOperand(Value *Operand, bool Static = false);
194 void writeInstComputationInline(Instruction &I);
195 void writeOperandInternal(Value *Operand, bool Static = false);
196 void writeOperandWithCast(Value* Operand, unsigned Opcode);
197 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
198 bool writeInstructionCast(const Instruction &I);
200 void writeMemoryAccess(Value *Operand, const Type *OperandType,
201 bool IsVolatile, unsigned Alignment);
204 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
206 void lowerIntrinsics(Function &F);
208 void printModule(Module *M);
209 void printModuleTypes(const TypeSymbolTable &ST);
210 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
211 void printFloatingPointConstants(Function &F);
212 void printFloatingPointConstants(const Constant *C);
213 void printFunctionSignature(const Function *F, bool Prototype);
215 void printFunction(Function &);
216 void printBasicBlock(BasicBlock *BB);
217 void printLoop(Loop *L);
219 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
220 void printConstant(Constant *CPV, bool Static);
221 void printConstantWithCast(Constant *CPV, unsigned Opcode);
222 bool printConstExprCast(const ConstantExpr *CE, bool Static);
223 void printConstantArray(ConstantArray *CPA, bool Static);
224 void printConstantVector(ConstantVector *CV, bool Static);
226 /// isAddressExposed - Return true if the specified value's name needs to
227 /// have its address taken in order to get a C value of the correct type.
228 /// This happens for global variables, byval parameters, and direct allocas.
229 bool isAddressExposed(const Value *V) const {
230 if (const Argument *A = dyn_cast<Argument>(V))
231 return ByValParams.count(A);
232 return isa<GlobalVariable>(V) || isDirectAlloca(V);
235 // isInlinableInst - Attempt to inline instructions into their uses to build
236 // trees as much as possible. To do this, we have to consistently decide
237 // what is acceptable to inline, so that variable declarations don't get
238 // printed and an extra copy of the expr is not emitted.
240 static bool isInlinableInst(const Instruction &I) {
241 // Always inline cmp instructions, even if they are shared by multiple
242 // expressions. GCC generates horrible code if we don't.
246 // Must be an expression, must be used exactly once. If it is dead, we
247 // emit it inline where it would go.
248 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
249 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
250 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
251 isa<InsertValueInst>(I))
252 // Don't inline a load across a store or other bad things!
255 // Must not be used in inline asm, extractelement, or shufflevector.
257 const Instruction &User = cast<Instruction>(*I.use_back());
258 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
259 isa<ShuffleVectorInst>(User))
263 // Only inline instruction it if it's use is in the same BB as the inst.
264 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
267 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
268 // variables which are accessed with the & operator. This causes GCC to
269 // generate significantly better code than to emit alloca calls directly.
271 static const AllocaInst *isDirectAlloca(const Value *V) {
272 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
273 if (!AI) return false;
274 if (AI->isArrayAllocation())
275 return 0; // FIXME: we can also inline fixed size array allocas!
276 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
281 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
282 static bool isInlineAsm(const Instruction& I) {
283 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
288 // Instruction visitation functions
289 friend class InstVisitor<CWriter>;
291 void visitReturnInst(ReturnInst &I);
292 void visitBranchInst(BranchInst &I);
293 void visitSwitchInst(SwitchInst &I);
294 void visitInvokeInst(InvokeInst &I) {
295 llvm_unreachable("Lowerinvoke pass didn't work!");
298 void visitUnwindInst(UnwindInst &I) {
299 llvm_unreachable("Lowerinvoke pass didn't work!");
301 void visitUnreachableInst(UnreachableInst &I);
303 void visitPHINode(PHINode &I);
304 void visitBinaryOperator(Instruction &I);
305 void visitICmpInst(ICmpInst &I);
306 void visitFCmpInst(FCmpInst &I);
308 void visitCastInst (CastInst &I);
309 void visitSelectInst(SelectInst &I);
310 void visitCallInst (CallInst &I);
311 void visitInlineAsm(CallInst &I);
312 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
314 void visitMallocInst(MallocInst &I);
315 void visitAllocaInst(AllocaInst &I);
316 void visitFreeInst (FreeInst &I);
317 void visitLoadInst (LoadInst &I);
318 void visitStoreInst (StoreInst &I);
319 void visitGetElementPtrInst(GetElementPtrInst &I);
320 void visitVAArgInst (VAArgInst &I);
322 void visitInsertElementInst(InsertElementInst &I);
323 void visitExtractElementInst(ExtractElementInst &I);
324 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
326 void visitInsertValueInst(InsertValueInst &I);
327 void visitExtractValueInst(ExtractValueInst &I);
329 void visitInstruction(Instruction &I) {
331 cerr << "C Writer does not know about " << I;
336 void outputLValue(Instruction *I) {
337 Out << " " << GetValueName(I) << " = ";
340 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
341 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
342 BasicBlock *Successor, unsigned Indent);
343 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
345 void printGEPExpression(Value *Ptr, gep_type_iterator I,
346 gep_type_iterator E, bool Static);
348 std::string GetValueName(const Value *Operand);
352 char CWriter::ID = 0;
354 /// This method inserts names for any unnamed structure types that are used by
355 /// the program, and removes names from structure types that are not used by the
358 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
359 // Get a set of types that are used by the program...
360 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
362 // Loop over the module symbol table, removing types from UT that are
363 // already named, and removing names for types that are not used.
365 TypeSymbolTable &TST = M.getTypeSymbolTable();
366 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
368 TypeSymbolTable::iterator I = TI++;
370 // If this isn't a struct or array type, remove it from our set of types
371 // to name. This simplifies emission later.
372 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
373 !isa<ArrayType>(I->second)) {
376 // If this is not used, remove it from the symbol table.
377 std::set<const Type *>::iterator UTI = UT.find(I->second);
381 UT.erase(UTI); // Only keep one name for this type.
385 // UT now contains types that are not named. Loop over it, naming
388 bool Changed = false;
389 unsigned RenameCounter = 0;
390 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
392 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
393 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
399 // Loop over all external functions and globals. If we have two with
400 // identical names, merge them.
401 // FIXME: This code should disappear when we don't allow values with the same
402 // names when they have different types!
403 std::map<std::string, GlobalValue*> ExtSymbols;
404 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
406 if (GV->isDeclaration() && GV->hasName()) {
407 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
408 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
410 // Found a conflict, replace this global with the previous one.
411 GlobalValue *OldGV = X.first->second;
412 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
413 GV->eraseFromParent();
418 // Do the same for globals.
419 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
421 GlobalVariable *GV = I++;
422 if (GV->isDeclaration() && GV->hasName()) {
423 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
424 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
426 // Found a conflict, replace this global with the previous one.
427 GlobalValue *OldGV = X.first->second;
428 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
429 GV->eraseFromParent();
438 /// printStructReturnPointerFunctionType - This is like printType for a struct
439 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
440 /// print it as "Struct (*)(...)", for struct return functions.
441 void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
442 const AttrListPtr &PAL,
443 const PointerType *TheTy) {
444 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
445 std::stringstream FunctionInnards;
446 FunctionInnards << " (*) (";
447 bool PrintedType = false;
449 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
450 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
452 for (++I, ++Idx; I != E; ++I, ++Idx) {
454 FunctionInnards << ", ";
455 const Type *ArgTy = *I;
456 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
457 assert(isa<PointerType>(ArgTy));
458 ArgTy = cast<PointerType>(ArgTy)->getElementType();
460 printType(FunctionInnards, ArgTy,
461 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
464 if (FTy->isVarArg()) {
466 FunctionInnards << ", ...";
467 } else if (!PrintedType) {
468 FunctionInnards << "void";
470 FunctionInnards << ')';
471 std::string tstr = FunctionInnards.str();
472 printType(Out, RetTy,
473 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
477 CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
479 const std::string &NameSoFar) {
480 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
481 "Invalid type for printSimpleType");
482 switch (Ty->getTypeID()) {
483 case Type::VoidTyID: return Out << "void " << NameSoFar;
484 case Type::IntegerTyID: {
485 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
487 return Out << "bool " << NameSoFar;
488 else if (NumBits <= 8)
489 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
490 else if (NumBits <= 16)
491 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
492 else if (NumBits <= 32)
493 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
494 else if (NumBits <= 64)
495 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
497 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
498 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
501 case Type::FloatTyID: return Out << "float " << NameSoFar;
502 case Type::DoubleTyID: return Out << "double " << NameSoFar;
503 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
504 // present matches host 'long double'.
505 case Type::X86_FP80TyID:
506 case Type::PPC_FP128TyID:
507 case Type::FP128TyID: return Out << "long double " << NameSoFar;
509 case Type::VectorTyID: {
510 const VectorType *VTy = cast<VectorType>(Ty);
511 return printSimpleType(Out, VTy->getElementType(), isSigned,
512 " __attribute__((vector_size(" +
513 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
518 cerr << "Unknown primitive type: " << *Ty << "\n";
525 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
526 const std::string &NameSoFar) {
527 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
528 "Invalid type for printSimpleType");
529 switch (Ty->getTypeID()) {
530 case Type::VoidTyID: return Out << "void " << NameSoFar;
531 case Type::IntegerTyID: {
532 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
534 return Out << "bool " << NameSoFar;
535 else if (NumBits <= 8)
536 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
537 else if (NumBits <= 16)
538 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
539 else if (NumBits <= 32)
540 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
541 else if (NumBits <= 64)
542 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
544 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
545 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
548 case Type::FloatTyID: return Out << "float " << NameSoFar;
549 case Type::DoubleTyID: return Out << "double " << NameSoFar;
550 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
551 // present matches host 'long double'.
552 case Type::X86_FP80TyID:
553 case Type::PPC_FP128TyID:
554 case Type::FP128TyID: return Out << "long double " << NameSoFar;
556 case Type::VectorTyID: {
557 const VectorType *VTy = cast<VectorType>(Ty);
558 return printSimpleType(Out, VTy->getElementType(), isSigned,
559 " __attribute__((vector_size(" +
560 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
565 cerr << "Unknown primitive type: " << *Ty << "\n";
571 // Pass the Type* and the variable name and this prints out the variable
574 raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
576 bool isSigned, const std::string &NameSoFar,
577 bool IgnoreName, const AttrListPtr &PAL) {
578 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
579 printSimpleType(Out, Ty, isSigned, NameSoFar);
583 // Check to see if the type is named.
584 if (!IgnoreName || isa<OpaqueType>(Ty)) {
585 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
586 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
589 switch (Ty->getTypeID()) {
590 case Type::FunctionTyID: {
591 const FunctionType *FTy = cast<FunctionType>(Ty);
592 std::stringstream FunctionInnards;
593 FunctionInnards << " (" << NameSoFar << ") (";
595 for (FunctionType::param_iterator I = FTy->param_begin(),
596 E = FTy->param_end(); I != E; ++I) {
597 const Type *ArgTy = *I;
598 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
599 assert(isa<PointerType>(ArgTy));
600 ArgTy = cast<PointerType>(ArgTy)->getElementType();
602 if (I != FTy->param_begin())
603 FunctionInnards << ", ";
604 printType(FunctionInnards, ArgTy,
605 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
608 if (FTy->isVarArg()) {
609 if (FTy->getNumParams())
610 FunctionInnards << ", ...";
611 } else if (!FTy->getNumParams()) {
612 FunctionInnards << "void";
614 FunctionInnards << ')';
615 std::string tstr = FunctionInnards.str();
616 printType(Out, FTy->getReturnType(),
617 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
620 case Type::StructTyID: {
621 const StructType *STy = cast<StructType>(Ty);
622 Out << NameSoFar + " {\n";
624 for (StructType::element_iterator I = STy->element_begin(),
625 E = STy->element_end(); I != E; ++I) {
627 printType(Out, *I, false, "field" + utostr(Idx++));
632 Out << " __attribute__ ((packed))";
636 case Type::PointerTyID: {
637 const PointerType *PTy = cast<PointerType>(Ty);
638 std::string ptrName = "*" + NameSoFar;
640 if (isa<ArrayType>(PTy->getElementType()) ||
641 isa<VectorType>(PTy->getElementType()))
642 ptrName = "(" + ptrName + ")";
645 // Must be a function ptr cast!
646 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
647 return printType(Out, PTy->getElementType(), false, ptrName);
650 case Type::ArrayTyID: {
651 const ArrayType *ATy = cast<ArrayType>(Ty);
652 unsigned NumElements = ATy->getNumElements();
653 if (NumElements == 0) NumElements = 1;
654 // Arrays are wrapped in structs to allow them to have normal
655 // value semantics (avoiding the array "decay").
656 Out << NameSoFar << " { ";
657 printType(Out, ATy->getElementType(), false,
658 "array[" + utostr(NumElements) + "]");
662 case Type::OpaqueTyID: {
663 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
664 assert(TypeNames.find(Ty) == TypeNames.end());
665 TypeNames[Ty] = TyName;
666 return Out << TyName << ' ' << NameSoFar;
669 llvm_unreachable("Unhandled case in getTypeProps!");
675 // Pass the Type* and the variable name and this prints out the variable
678 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
679 bool isSigned, const std::string &NameSoFar,
680 bool IgnoreName, const AttrListPtr &PAL) {
681 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
682 printSimpleType(Out, Ty, isSigned, NameSoFar);
686 // Check to see if the type is named.
687 if (!IgnoreName || isa<OpaqueType>(Ty)) {
688 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
689 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
692 switch (Ty->getTypeID()) {
693 case Type::FunctionTyID: {
694 const FunctionType *FTy = cast<FunctionType>(Ty);
695 std::stringstream FunctionInnards;
696 FunctionInnards << " (" << NameSoFar << ") (";
698 for (FunctionType::param_iterator I = FTy->param_begin(),
699 E = FTy->param_end(); I != E; ++I) {
700 const Type *ArgTy = *I;
701 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
702 assert(isa<PointerType>(ArgTy));
703 ArgTy = cast<PointerType>(ArgTy)->getElementType();
705 if (I != FTy->param_begin())
706 FunctionInnards << ", ";
707 printType(FunctionInnards, ArgTy,
708 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
711 if (FTy->isVarArg()) {
712 if (FTy->getNumParams())
713 FunctionInnards << ", ...";
714 } else if (!FTy->getNumParams()) {
715 FunctionInnards << "void";
717 FunctionInnards << ')';
718 std::string tstr = FunctionInnards.str();
719 printType(Out, FTy->getReturnType(),
720 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
723 case Type::StructTyID: {
724 const StructType *STy = cast<StructType>(Ty);
725 Out << NameSoFar + " {\n";
727 for (StructType::element_iterator I = STy->element_begin(),
728 E = STy->element_end(); I != E; ++I) {
730 printType(Out, *I, false, "field" + utostr(Idx++));
735 Out << " __attribute__ ((packed))";
739 case Type::PointerTyID: {
740 const PointerType *PTy = cast<PointerType>(Ty);
741 std::string ptrName = "*" + NameSoFar;
743 if (isa<ArrayType>(PTy->getElementType()) ||
744 isa<VectorType>(PTy->getElementType()))
745 ptrName = "(" + ptrName + ")";
748 // Must be a function ptr cast!
749 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
750 return printType(Out, PTy->getElementType(), false, ptrName);
753 case Type::ArrayTyID: {
754 const ArrayType *ATy = cast<ArrayType>(Ty);
755 unsigned NumElements = ATy->getNumElements();
756 if (NumElements == 0) NumElements = 1;
757 // Arrays are wrapped in structs to allow them to have normal
758 // value semantics (avoiding the array "decay").
759 Out << NameSoFar << " { ";
760 printType(Out, ATy->getElementType(), false,
761 "array[" + utostr(NumElements) + "]");
765 case Type::OpaqueTyID: {
766 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
767 assert(TypeNames.find(Ty) == TypeNames.end());
768 TypeNames[Ty] = TyName;
769 return Out << TyName << ' ' << NameSoFar;
772 llvm_unreachable("Unhandled case in getTypeProps!");
778 void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
780 // As a special case, print the array as a string if it is an array of
781 // ubytes or an array of sbytes with positive values.
783 const Type *ETy = CPA->getType()->getElementType();
784 bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty);
786 // Make sure the last character is a null char, as automatically added by C
787 if (isString && (CPA->getNumOperands() == 0 ||
788 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
793 // Keep track of whether the last number was a hexadecimal escape
794 bool LastWasHex = false;
796 // Do not include the last character, which we know is null
797 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
798 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
800 // Print it out literally if it is a printable character. The only thing
801 // to be careful about is when the last letter output was a hex escape
802 // code, in which case we have to be careful not to print out hex digits
803 // explicitly (the C compiler thinks it is a continuation of the previous
804 // character, sheesh...)
806 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
808 if (C == '"' || C == '\\')
809 Out << "\\" << (char)C;
815 case '\n': Out << "\\n"; break;
816 case '\t': Out << "\\t"; break;
817 case '\r': Out << "\\r"; break;
818 case '\v': Out << "\\v"; break;
819 case '\a': Out << "\\a"; break;
820 case '\"': Out << "\\\""; break;
821 case '\'': Out << "\\\'"; break;
824 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
825 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
834 if (CPA->getNumOperands()) {
836 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
837 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
839 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
846 void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
848 if (CP->getNumOperands()) {
850 printConstant(cast<Constant>(CP->getOperand(0)), Static);
851 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
853 printConstant(cast<Constant>(CP->getOperand(i)), Static);
859 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
860 // textually as a double (rather than as a reference to a stack-allocated
861 // variable). We decide this by converting CFP to a string and back into a
862 // double, and then checking whether the conversion results in a bit-equal
863 // double to the original value of CFP. This depends on us and the target C
864 // compiler agreeing on the conversion process (which is pretty likely since we
865 // only deal in IEEE FP).
867 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
869 // Do long doubles in hex for now.
870 if (CFP->getType() != Type::FloatTy && CFP->getType() != Type::DoubleTy)
872 APFloat APF = APFloat(CFP->getValueAPF()); // copy
873 if (CFP->getType() == Type::FloatTy)
874 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
875 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
877 sprintf(Buffer, "%a", APF.convertToDouble());
878 if (!strncmp(Buffer, "0x", 2) ||
879 !strncmp(Buffer, "-0x", 3) ||
880 !strncmp(Buffer, "+0x", 3))
881 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
884 std::string StrVal = ftostr(APF);
886 while (StrVal[0] == ' ')
887 StrVal.erase(StrVal.begin());
889 // Check to make sure that the stringized number is not some string like "Inf"
890 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
891 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
892 ((StrVal[0] == '-' || StrVal[0] == '+') &&
893 (StrVal[1] >= '0' && StrVal[1] <= '9')))
894 // Reparse stringized version!
895 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
900 /// Print out the casting for a cast operation. This does the double casting
901 /// necessary for conversion to the destination type, if necessary.
902 /// @brief Print a cast
903 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
904 // Print the destination type cast
906 case Instruction::UIToFP:
907 case Instruction::SIToFP:
908 case Instruction::IntToPtr:
909 case Instruction::Trunc:
910 case Instruction::BitCast:
911 case Instruction::FPExt:
912 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
914 printType(Out, DstTy);
917 case Instruction::ZExt:
918 case Instruction::PtrToInt:
919 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
921 printSimpleType(Out, DstTy, false);
924 case Instruction::SExt:
925 case Instruction::FPToSI: // For these, make sure we get a signed dest
927 printSimpleType(Out, DstTy, true);
931 llvm_unreachable("Invalid cast opcode");
934 // Print the source type cast
936 case Instruction::UIToFP:
937 case Instruction::ZExt:
939 printSimpleType(Out, SrcTy, false);
942 case Instruction::SIToFP:
943 case Instruction::SExt:
945 printSimpleType(Out, SrcTy, true);
948 case Instruction::IntToPtr:
949 case Instruction::PtrToInt:
950 // Avoid "cast to pointer from integer of different size" warnings
951 Out << "(unsigned long)";
953 case Instruction::Trunc:
954 case Instruction::BitCast:
955 case Instruction::FPExt:
956 case Instruction::FPTrunc:
957 case Instruction::FPToSI:
958 case Instruction::FPToUI:
959 break; // These don't need a source cast.
961 llvm_unreachable("Invalid cast opcode");
966 // printConstant - The LLVM Constant to C Constant converter.
967 void CWriter::printConstant(Constant *CPV, bool Static) {
968 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
969 switch (CE->getOpcode()) {
970 case Instruction::Trunc:
971 case Instruction::ZExt:
972 case Instruction::SExt:
973 case Instruction::FPTrunc:
974 case Instruction::FPExt:
975 case Instruction::UIToFP:
976 case Instruction::SIToFP:
977 case Instruction::FPToUI:
978 case Instruction::FPToSI:
979 case Instruction::PtrToInt:
980 case Instruction::IntToPtr:
981 case Instruction::BitCast:
983 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
984 if (CE->getOpcode() == Instruction::SExt &&
985 CE->getOperand(0)->getType() == Type::Int1Ty) {
986 // Make sure we really sext from bool here by subtracting from 0
989 printConstant(CE->getOperand(0), Static);
990 if (CE->getType() == Type::Int1Ty &&
991 (CE->getOpcode() == Instruction::Trunc ||
992 CE->getOpcode() == Instruction::FPToUI ||
993 CE->getOpcode() == Instruction::FPToSI ||
994 CE->getOpcode() == Instruction::PtrToInt)) {
995 // Make sure we really truncate to bool here by anding with 1
1001 case Instruction::GetElementPtr:
1003 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
1004 gep_type_end(CPV), Static);
1007 case Instruction::Select:
1009 printConstant(CE->getOperand(0), Static);
1011 printConstant(CE->getOperand(1), Static);
1013 printConstant(CE->getOperand(2), Static);
1016 case Instruction::Add:
1017 case Instruction::FAdd:
1018 case Instruction::Sub:
1019 case Instruction::FSub:
1020 case Instruction::Mul:
1021 case Instruction::FMul:
1022 case Instruction::SDiv:
1023 case Instruction::UDiv:
1024 case Instruction::FDiv:
1025 case Instruction::URem:
1026 case Instruction::SRem:
1027 case Instruction::FRem:
1028 case Instruction::And:
1029 case Instruction::Or:
1030 case Instruction::Xor:
1031 case Instruction::ICmp:
1032 case Instruction::Shl:
1033 case Instruction::LShr:
1034 case Instruction::AShr:
1037 bool NeedsClosingParens = printConstExprCast(CE, Static);
1038 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1039 switch (CE->getOpcode()) {
1040 case Instruction::Add:
1041 case Instruction::FAdd: Out << " + "; break;
1042 case Instruction::Sub:
1043 case Instruction::FSub: Out << " - "; break;
1044 case Instruction::Mul:
1045 case Instruction::FMul: Out << " * "; break;
1046 case Instruction::URem:
1047 case Instruction::SRem:
1048 case Instruction::FRem: Out << " % "; break;
1049 case Instruction::UDiv:
1050 case Instruction::SDiv:
1051 case Instruction::FDiv: Out << " / "; break;
1052 case Instruction::And: Out << " & "; break;
1053 case Instruction::Or: Out << " | "; break;
1054 case Instruction::Xor: Out << " ^ "; break;
1055 case Instruction::Shl: Out << " << "; break;
1056 case Instruction::LShr:
1057 case Instruction::AShr: Out << " >> "; break;
1058 case Instruction::ICmp:
1059 switch (CE->getPredicate()) {
1060 case ICmpInst::ICMP_EQ: Out << " == "; break;
1061 case ICmpInst::ICMP_NE: Out << " != "; break;
1062 case ICmpInst::ICMP_SLT:
1063 case ICmpInst::ICMP_ULT: Out << " < "; break;
1064 case ICmpInst::ICMP_SLE:
1065 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1066 case ICmpInst::ICMP_SGT:
1067 case ICmpInst::ICMP_UGT: Out << " > "; break;
1068 case ICmpInst::ICMP_SGE:
1069 case ICmpInst::ICMP_UGE: Out << " >= "; break;
1070 default: llvm_unreachable("Illegal ICmp predicate");
1073 default: llvm_unreachable("Illegal opcode here!");
1075 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1076 if (NeedsClosingParens)
1081 case Instruction::FCmp: {
1083 bool NeedsClosingParens = printConstExprCast(CE, Static);
1084 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1086 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1090 switch (CE->getPredicate()) {
1091 default: llvm_unreachable("Illegal FCmp predicate");
1092 case FCmpInst::FCMP_ORD: op = "ord"; break;
1093 case FCmpInst::FCMP_UNO: op = "uno"; break;
1094 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1095 case FCmpInst::FCMP_UNE: op = "une"; break;
1096 case FCmpInst::FCMP_ULT: op = "ult"; break;
1097 case FCmpInst::FCMP_ULE: op = "ule"; break;
1098 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1099 case FCmpInst::FCMP_UGE: op = "uge"; break;
1100 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1101 case FCmpInst::FCMP_ONE: op = "one"; break;
1102 case FCmpInst::FCMP_OLT: op = "olt"; break;
1103 case FCmpInst::FCMP_OLE: op = "ole"; break;
1104 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1105 case FCmpInst::FCMP_OGE: op = "oge"; break;
1107 Out << "llvm_fcmp_" << op << "(";
1108 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1110 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1113 if (NeedsClosingParens)
1120 cerr << "CWriter Error: Unhandled constant expression: "
1123 llvm_unreachable(0);
1125 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
1127 printType(Out, CPV->getType()); // sign doesn't matter
1128 Out << ")/*UNDEF*/";
1129 if (!isa<VectorType>(CPV->getType())) {
1137 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1138 const Type* Ty = CI->getType();
1139 if (Ty == Type::Int1Ty)
1140 Out << (CI->getZExtValue() ? '1' : '0');
1141 else if (Ty == Type::Int32Ty)
1142 Out << CI->getZExtValue() << 'u';
1143 else if (Ty->getPrimitiveSizeInBits() > 32)
1144 Out << CI->getZExtValue() << "ull";
1147 printSimpleType(Out, Ty, false) << ')';
1148 if (CI->isMinValue(true))
1149 Out << CI->getZExtValue() << 'u';
1151 Out << CI->getSExtValue();
1157 switch (CPV->getType()->getTypeID()) {
1158 case Type::FloatTyID:
1159 case Type::DoubleTyID:
1160 case Type::X86_FP80TyID:
1161 case Type::PPC_FP128TyID:
1162 case Type::FP128TyID: {
1163 ConstantFP *FPC = cast<ConstantFP>(CPV);
1164 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
1165 if (I != FPConstantMap.end()) {
1166 // Because of FP precision problems we must load from a stack allocated
1167 // value that holds the value in hex.
1168 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" :
1169 FPC->getType() == Type::DoubleTy ? "double" :
1171 << "*)&FPConstant" << I->second << ')';
1174 if (FPC->getType() == Type::FloatTy)
1175 V = FPC->getValueAPF().convertToFloat();
1176 else if (FPC->getType() == Type::DoubleTy)
1177 V = FPC->getValueAPF().convertToDouble();
1179 // Long double. Convert the number to double, discarding precision.
1180 // This is not awesome, but it at least makes the CBE output somewhat
1182 APFloat Tmp = FPC->getValueAPF();
1184 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1185 V = Tmp.convertToDouble();
1191 // FIXME the actual NaN bits should be emitted.
1192 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1194 const unsigned long QuietNaN = 0x7ff8UL;
1195 //const unsigned long SignalNaN = 0x7ff4UL;
1197 // We need to grab the first part of the FP #
1200 uint64_t ll = DoubleToBits(V);
1201 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
1203 std::string Num(&Buffer[0], &Buffer[6]);
1204 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1206 if (FPC->getType() == Type::FloatTy)
1207 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1208 << Buffer << "\") /*nan*/ ";
1210 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1211 << Buffer << "\") /*nan*/ ";
1212 } else if (IsInf(V)) {
1214 if (V < 0) Out << '-';
1215 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
1219 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1220 // Print out the constant as a floating point number.
1222 sprintf(Buffer, "%a", V);
1225 Num = ftostr(FPC->getValueAPF());
1233 case Type::ArrayTyID:
1234 // Use C99 compound expression literal initializer syntax.
1237 printType(Out, CPV->getType());
1240 Out << "{ "; // Arrays are wrapped in struct types.
1241 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
1242 printConstantArray(CA, Static);
1244 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1245 const ArrayType *AT = cast<ArrayType>(CPV->getType());
1247 if (AT->getNumElements()) {
1249 Constant *CZ = Context->getNullValue(AT->getElementType());
1250 printConstant(CZ, Static);
1251 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1253 printConstant(CZ, Static);
1258 Out << " }"; // Arrays are wrapped in struct types.
1261 case Type::VectorTyID:
1262 // Use C99 compound expression literal initializer syntax.
1265 printType(Out, CPV->getType());
1268 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
1269 printConstantVector(CV, Static);
1271 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1272 const VectorType *VT = cast<VectorType>(CPV->getType());
1274 Constant *CZ = Context->getNullValue(VT->getElementType());
1275 printConstant(CZ, Static);
1276 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
1278 printConstant(CZ, Static);
1284 case Type::StructTyID:
1285 // Use C99 compound expression literal initializer syntax.
1288 printType(Out, CPV->getType());
1291 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1292 const StructType *ST = cast<StructType>(CPV->getType());
1294 if (ST->getNumElements()) {
1296 printConstant(Context->getNullValue(ST->getElementType(0)), Static);
1297 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1299 printConstant(Context->getNullValue(ST->getElementType(i)), Static);
1305 if (CPV->getNumOperands()) {
1307 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
1308 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1310 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
1317 case Type::PointerTyID:
1318 if (isa<ConstantPointerNull>(CPV)) {
1320 printType(Out, CPV->getType()); // sign doesn't matter
1321 Out << ")/*NULL*/0)";
1323 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1324 writeOperand(GV, Static);
1330 cerr << "Unknown constant type: " << *CPV << "\n";
1332 llvm_unreachable(0);
1336 // Some constant expressions need to be casted back to the original types
1337 // because their operands were casted to the expected type. This function takes
1338 // care of detecting that case and printing the cast for the ConstantExpr.
1339 bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
1340 bool NeedsExplicitCast = false;
1341 const Type *Ty = CE->getOperand(0)->getType();
1342 bool TypeIsSigned = false;
1343 switch (CE->getOpcode()) {
1344 case Instruction::Add:
1345 case Instruction::Sub:
1346 case Instruction::Mul:
1347 // We need to cast integer arithmetic so that it is always performed
1348 // as unsigned, to avoid undefined behavior on overflow.
1349 case Instruction::LShr:
1350 case Instruction::URem:
1351 case Instruction::UDiv: NeedsExplicitCast = true; break;
1352 case Instruction::AShr:
1353 case Instruction::SRem:
1354 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1355 case Instruction::SExt:
1357 NeedsExplicitCast = true;
1358 TypeIsSigned = true;
1360 case Instruction::ZExt:
1361 case Instruction::Trunc:
1362 case Instruction::FPTrunc:
1363 case Instruction::FPExt:
1364 case Instruction::UIToFP:
1365 case Instruction::SIToFP:
1366 case Instruction::FPToUI:
1367 case Instruction::FPToSI:
1368 case Instruction::PtrToInt:
1369 case Instruction::IntToPtr:
1370 case Instruction::BitCast:
1372 NeedsExplicitCast = true;
1376 if (NeedsExplicitCast) {
1378 if (Ty->isInteger() && Ty != Type::Int1Ty)
1379 printSimpleType(Out, Ty, TypeIsSigned);
1381 printType(Out, Ty); // not integer, sign doesn't matter
1384 return NeedsExplicitCast;
1387 // Print a constant assuming that it is the operand for a given Opcode. The
1388 // opcodes that care about sign need to cast their operands to the expected
1389 // type before the operation proceeds. This function does the casting.
1390 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1392 // Extract the operand's type, we'll need it.
1393 const Type* OpTy = CPV->getType();
1395 // Indicate whether to do the cast or not.
1396 bool shouldCast = false;
1397 bool typeIsSigned = false;
1399 // Based on the Opcode for which this Constant is being written, determine
1400 // the new type to which the operand should be casted by setting the value
1401 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1405 // for most instructions, it doesn't matter
1407 case Instruction::Add:
1408 case Instruction::Sub:
1409 case Instruction::Mul:
1410 // We need to cast integer arithmetic so that it is always performed
1411 // as unsigned, to avoid undefined behavior on overflow.
1412 case Instruction::LShr:
1413 case Instruction::UDiv:
1414 case Instruction::URem:
1417 case Instruction::AShr:
1418 case Instruction::SDiv:
1419 case Instruction::SRem:
1421 typeIsSigned = true;
1425 // Write out the casted constant if we should, otherwise just write the
1429 printSimpleType(Out, OpTy, typeIsSigned);
1431 printConstant(CPV, false);
1434 printConstant(CPV, false);
1437 std::string CWriter::GetValueName(const Value *Operand) {
1438 // Mangle globals with the standard mangler interface for LLC compatibility.
1439 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand))
1440 return Mang->getMangledName(GV);
1442 std::string Name = Operand->getName();
1444 if (Name.empty()) { // Assign unique names to local temporaries.
1445 unsigned &No = AnonValueNumbers[Operand];
1447 No = ++NextAnonValueNumber;
1448 Name = "tmp__" + utostr(No);
1451 std::string VarName;
1452 VarName.reserve(Name.capacity());
1454 for (std::string::iterator I = Name.begin(), E = Name.end();
1458 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1459 (ch >= '0' && ch <= '9') || ch == '_')) {
1461 sprintf(buffer, "_%x_", ch);
1467 return "llvm_cbe_" + VarName;
1470 /// writeInstComputationInline - Emit the computation for the specified
1471 /// instruction inline, with no destination provided.
1472 void CWriter::writeInstComputationInline(Instruction &I) {
1473 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1475 const Type *Ty = I.getType();
1476 if (Ty->isInteger() && (Ty!=Type::Int1Ty && Ty!=Type::Int8Ty &&
1477 Ty!=Type::Int16Ty && Ty!=Type::Int32Ty && Ty!=Type::Int64Ty)) {
1478 llvm_report_error("The C backend does not currently support integer "
1479 "types of widths other than 1, 8, 16, 32, 64.\n"
1480 "This is being tracked as PR 4158.");
1483 // If this is a non-trivial bool computation, make sure to truncate down to
1484 // a 1 bit value. This is important because we want "add i1 x, y" to return
1485 // "0" when x and y are true, not "2" for example.
1486 bool NeedBoolTrunc = false;
1487 if (I.getType() == Type::Int1Ty && !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
1488 NeedBoolTrunc = true;
1500 void CWriter::writeOperandInternal(Value *Operand, bool Static) {
1501 if (Instruction *I = dyn_cast<Instruction>(Operand))
1502 // Should we inline this instruction to build a tree?
1503 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1505 writeInstComputationInline(*I);
1510 Constant* CPV = dyn_cast<Constant>(Operand);
1512 if (CPV && !isa<GlobalValue>(CPV))
1513 printConstant(CPV, Static);
1515 Out << GetValueName(Operand);
1518 void CWriter::writeOperand(Value *Operand, bool Static) {
1519 bool isAddressImplicit = isAddressExposed(Operand);
1520 if (isAddressImplicit)
1521 Out << "(&"; // Global variables are referenced as their addresses by llvm
1523 writeOperandInternal(Operand, Static);
1525 if (isAddressImplicit)
1529 // Some instructions need to have their result value casted back to the
1530 // original types because their operands were casted to the expected type.
1531 // This function takes care of detecting that case and printing the cast
1532 // for the Instruction.
1533 bool CWriter::writeInstructionCast(const Instruction &I) {
1534 const Type *Ty = I.getOperand(0)->getType();
1535 switch (I.getOpcode()) {
1536 case Instruction::Add:
1537 case Instruction::Sub:
1538 case Instruction::Mul:
1539 // We need to cast integer arithmetic so that it is always performed
1540 // as unsigned, to avoid undefined behavior on overflow.
1541 case Instruction::LShr:
1542 case Instruction::URem:
1543 case Instruction::UDiv:
1545 printSimpleType(Out, Ty, false);
1548 case Instruction::AShr:
1549 case Instruction::SRem:
1550 case Instruction::SDiv:
1552 printSimpleType(Out, Ty, true);
1560 // Write the operand with a cast to another type based on the Opcode being used.
1561 // This will be used in cases where an instruction has specific type
1562 // requirements (usually signedness) for its operands.
1563 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1565 // Extract the operand's type, we'll need it.
1566 const Type* OpTy = Operand->getType();
1568 // Indicate whether to do the cast or not.
1569 bool shouldCast = false;
1571 // Indicate whether the cast should be to a signed type or not.
1572 bool castIsSigned = false;
1574 // Based on the Opcode for which this Operand is being written, determine
1575 // the new type to which the operand should be casted by setting the value
1576 // of OpTy. If we change OpTy, also set shouldCast to true.
1579 // for most instructions, it doesn't matter
1581 case Instruction::Add:
1582 case Instruction::Sub:
1583 case Instruction::Mul:
1584 // We need to cast integer arithmetic so that it is always performed
1585 // as unsigned, to avoid undefined behavior on overflow.
1586 case Instruction::LShr:
1587 case Instruction::UDiv:
1588 case Instruction::URem: // Cast to unsigned first
1590 castIsSigned = false;
1592 case Instruction::GetElementPtr:
1593 case Instruction::AShr:
1594 case Instruction::SDiv:
1595 case Instruction::SRem: // Cast to signed first
1597 castIsSigned = true;
1601 // Write out the casted operand if we should, otherwise just write the
1605 printSimpleType(Out, OpTy, castIsSigned);
1607 writeOperand(Operand);
1610 writeOperand(Operand);
1613 // Write the operand with a cast to another type based on the icmp predicate
1615 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1616 // This has to do a cast to ensure the operand has the right signedness.
1617 // Also, if the operand is a pointer, we make sure to cast to an integer when
1618 // doing the comparison both for signedness and so that the C compiler doesn't
1619 // optimize things like "p < NULL" to false (p may contain an integer value
1621 bool shouldCast = Cmp.isRelational();
1623 // Write out the casted operand if we should, otherwise just write the
1626 writeOperand(Operand);
1630 // Should this be a signed comparison? If so, convert to signed.
1631 bool castIsSigned = Cmp.isSignedPredicate();
1633 // If the operand was a pointer, convert to a large integer type.
1634 const Type* OpTy = Operand->getType();
1635 if (isa<PointerType>(OpTy))
1636 OpTy = TD->getIntPtrType();
1639 printSimpleType(Out, OpTy, castIsSigned);
1641 writeOperand(Operand);
1645 // generateCompilerSpecificCode - This is where we add conditional compilation
1646 // directives to cater to specific compilers as need be.
1648 static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
1649 const TargetData *TD) {
1650 // Alloca is hard to get, and we don't want to include stdlib.h here.
1651 Out << "/* get a declaration for alloca */\n"
1652 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1653 << "#define alloca(x) __builtin_alloca((x))\n"
1654 << "#define _alloca(x) __builtin_alloca((x))\n"
1655 << "#elif defined(__APPLE__)\n"
1656 << "extern void *__builtin_alloca(unsigned long);\n"
1657 << "#define alloca(x) __builtin_alloca(x)\n"
1658 << "#define longjmp _longjmp\n"
1659 << "#define setjmp _setjmp\n"
1660 << "#elif defined(__sun__)\n"
1661 << "#if defined(__sparcv9)\n"
1662 << "extern void *__builtin_alloca(unsigned long);\n"
1664 << "extern void *__builtin_alloca(unsigned int);\n"
1666 << "#define alloca(x) __builtin_alloca(x)\n"
1667 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)\n"
1668 << "#define alloca(x) __builtin_alloca(x)\n"
1669 << "#elif defined(_MSC_VER)\n"
1670 << "#define inline _inline\n"
1671 << "#define alloca(x) _alloca(x)\n"
1673 << "#include <alloca.h>\n"
1676 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1677 // If we aren't being compiled with GCC, just drop these attributes.
1678 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1679 << "#define __attribute__(X)\n"
1682 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1683 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1684 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1685 << "#elif defined(__GNUC__)\n"
1686 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1688 << "#define __EXTERNAL_WEAK__\n"
1691 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1692 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1693 << "#define __ATTRIBUTE_WEAK__\n"
1694 << "#elif defined(__GNUC__)\n"
1695 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1697 << "#define __ATTRIBUTE_WEAK__\n"
1700 // Add hidden visibility support. FIXME: APPLE_CC?
1701 Out << "#if defined(__GNUC__)\n"
1702 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1705 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1706 // From the GCC documentation:
1708 // double __builtin_nan (const char *str)
1710 // This is an implementation of the ISO C99 function nan.
1712 // Since ISO C99 defines this function in terms of strtod, which we do
1713 // not implement, a description of the parsing is in order. The string is
1714 // parsed as by strtol; that is, the base is recognized by leading 0 or
1715 // 0x prefixes. The number parsed is placed in the significand such that
1716 // the least significant bit of the number is at the least significant
1717 // bit of the significand. The number is truncated to fit the significand
1718 // field provided. The significand is forced to be a quiet NaN.
1720 // This function, if given a string literal, is evaluated early enough
1721 // that it is considered a compile-time constant.
1723 // float __builtin_nanf (const char *str)
1725 // Similar to __builtin_nan, except the return type is float.
1727 // double __builtin_inf (void)
1729 // Similar to __builtin_huge_val, except a warning is generated if the
1730 // target floating-point format does not support infinities. This
1731 // function is suitable for implementing the ISO C99 macro INFINITY.
1733 // float __builtin_inff (void)
1735 // Similar to __builtin_inf, except the return type is float.
1736 Out << "#ifdef __GNUC__\n"
1737 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1738 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1739 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1740 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1741 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1742 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1743 << "#define LLVM_PREFETCH(addr,rw,locality) "
1744 "__builtin_prefetch(addr,rw,locality)\n"
1745 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1746 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1747 << "#define LLVM_ASM __asm__\n"
1749 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1750 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1751 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1752 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1753 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1754 << "#define LLVM_INFF 0.0F /* Float */\n"
1755 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1756 << "#define __ATTRIBUTE_CTOR__\n"
1757 << "#define __ATTRIBUTE_DTOR__\n"
1758 << "#define LLVM_ASM(X)\n"
1761 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1762 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1763 << "#define __builtin_stack_restore(X) /* noop */\n"
1766 // Output typedefs for 128-bit integers. If these are needed with a
1767 // 32-bit target or with a C compiler that doesn't support mode(TI),
1768 // more drastic measures will be needed.
1769 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1770 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1771 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1774 // Output target-specific code that should be inserted into main.
1775 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1778 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1779 /// the StaticTors set.
1780 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1781 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1782 if (!InitList) return;
1784 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1785 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1786 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1788 if (CS->getOperand(1)->isNullValue())
1789 return; // Found a null terminator, exit printing.
1790 Constant *FP = CS->getOperand(1);
1791 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1793 FP = CE->getOperand(0);
1794 if (Function *F = dyn_cast<Function>(FP))
1795 StaticTors.insert(F);
1799 enum SpecialGlobalClass {
1801 GlobalCtors, GlobalDtors,
1805 /// getGlobalVariableClass - If this is a global that is specially recognized
1806 /// by LLVM, return a code that indicates how we should handle it.
1807 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1808 // If this is a global ctors/dtors list, handle it now.
1809 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1810 if (GV->getName() == "llvm.global_ctors")
1812 else if (GV->getName() == "llvm.global_dtors")
1816 // Otherwise, it it is other metadata, don't print it. This catches things
1817 // like debug information.
1818 if (GV->getSection() == "llvm.metadata")
1825 bool CWriter::doInitialization(Module &M) {
1829 TD = new TargetData(&M);
1830 IL = new IntrinsicLowering(*TD);
1831 IL->AddPrototypes(M);
1833 // Ensure that all structure types have names...
1834 Mang = new Mangler(M);
1835 Mang->markCharUnacceptable('.');
1837 // Keep track of which functions are static ctors/dtors so they can have
1838 // an attribute added to their prototypes.
1839 std::set<Function*> StaticCtors, StaticDtors;
1840 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1842 switch (getGlobalVariableClass(I)) {
1845 FindStaticTors(I, StaticCtors);
1848 FindStaticTors(I, StaticDtors);
1853 // get declaration for alloca
1854 Out << "/* Provide Declarations */\n";
1855 Out << "#include <stdarg.h>\n"; // Varargs support
1856 Out << "#include <setjmp.h>\n"; // Unwind support
1857 generateCompilerSpecificCode(Out, TD);
1859 // Provide a definition for `bool' if not compiling with a C++ compiler.
1861 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1863 << "\n\n/* Support for floating point constants */\n"
1864 << "typedef unsigned long long ConstantDoubleTy;\n"
1865 << "typedef unsigned int ConstantFloatTy;\n"
1866 << "typedef struct { unsigned long long f1; unsigned short f2; "
1867 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1868 // This is used for both kinds of 128-bit long double; meaning differs.
1869 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1870 " ConstantFP128Ty;\n"
1871 << "\n\n/* Global Declarations */\n";
1873 // First output all the declarations for the program, because C requires
1874 // Functions & globals to be declared before they are used.
1877 // Loop over the symbol table, emitting all named constants...
1878 printModuleTypes(M.getTypeSymbolTable());
1880 // Global variable declarations...
1881 if (!M.global_empty()) {
1882 Out << "\n/* External Global Variable Declarations */\n";
1883 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1886 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1887 I->hasCommonLinkage())
1889 else if (I->hasDLLImportLinkage())
1890 Out << "__declspec(dllimport) ";
1892 continue; // Internal Global
1894 // Thread Local Storage
1895 if (I->isThreadLocal())
1898 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1900 if (I->hasExternalWeakLinkage())
1901 Out << " __EXTERNAL_WEAK__";
1906 // Function declarations
1907 Out << "\n/* Function Declarations */\n";
1908 Out << "double fmod(double, double);\n"; // Support for FP rem
1909 Out << "float fmodf(float, float);\n";
1910 Out << "long double fmodl(long double, long double);\n";
1912 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1913 // Don't print declarations for intrinsic functions.
1914 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
1915 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1916 if (I->hasExternalWeakLinkage())
1918 printFunctionSignature(I, true);
1919 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1920 Out << " __ATTRIBUTE_WEAK__";
1921 if (I->hasExternalWeakLinkage())
1922 Out << " __EXTERNAL_WEAK__";
1923 if (StaticCtors.count(I))
1924 Out << " __ATTRIBUTE_CTOR__";
1925 if (StaticDtors.count(I))
1926 Out << " __ATTRIBUTE_DTOR__";
1927 if (I->hasHiddenVisibility())
1928 Out << " __HIDDEN__";
1930 if (I->hasName() && I->getName()[0] == 1)
1931 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1937 // Output the global variable declarations
1938 if (!M.global_empty()) {
1939 Out << "\n\n/* Global Variable Declarations */\n";
1940 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1942 if (!I->isDeclaration()) {
1943 // Ignore special globals, such as debug info.
1944 if (getGlobalVariableClass(I))
1947 if (I->hasLocalLinkage())
1952 // Thread Local Storage
1953 if (I->isThreadLocal())
1956 printType(Out, I->getType()->getElementType(), false,
1959 if (I->hasLinkOnceLinkage())
1960 Out << " __attribute__((common))";
1961 else if (I->hasCommonLinkage()) // FIXME is this right?
1962 Out << " __ATTRIBUTE_WEAK__";
1963 else if (I->hasWeakLinkage())
1964 Out << " __ATTRIBUTE_WEAK__";
1965 else if (I->hasExternalWeakLinkage())
1966 Out << " __EXTERNAL_WEAK__";
1967 if (I->hasHiddenVisibility())
1968 Out << " __HIDDEN__";
1973 // Output the global variable definitions and contents...
1974 if (!M.global_empty()) {
1975 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1976 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1978 if (!I->isDeclaration()) {
1979 // Ignore special globals, such as debug info.
1980 if (getGlobalVariableClass(I))
1983 if (I->hasLocalLinkage())
1985 else if (I->hasDLLImportLinkage())
1986 Out << "__declspec(dllimport) ";
1987 else if (I->hasDLLExportLinkage())
1988 Out << "__declspec(dllexport) ";
1990 // Thread Local Storage
1991 if (I->isThreadLocal())
1994 printType(Out, I->getType()->getElementType(), false,
1996 if (I->hasLinkOnceLinkage())
1997 Out << " __attribute__((common))";
1998 else if (I->hasWeakLinkage())
1999 Out << " __ATTRIBUTE_WEAK__";
2000 else if (I->hasCommonLinkage())
2001 Out << " __ATTRIBUTE_WEAK__";
2003 if (I->hasHiddenVisibility())
2004 Out << " __HIDDEN__";
2006 // If the initializer is not null, emit the initializer. If it is null,
2007 // we try to avoid emitting large amounts of zeros. The problem with
2008 // this, however, occurs when the variable has weak linkage. In this
2009 // case, the assembler will complain about the variable being both weak
2010 // and common, so we disable this optimization.
2011 // FIXME common linkage should avoid this problem.
2012 if (!I->getInitializer()->isNullValue()) {
2014 writeOperand(I->getInitializer(), true);
2015 } else if (I->hasWeakLinkage()) {
2016 // We have to specify an initializer, but it doesn't have to be
2017 // complete. If the value is an aggregate, print out { 0 }, and let
2018 // the compiler figure out the rest of the zeros.
2020 if (isa<StructType>(I->getInitializer()->getType()) ||
2021 isa<VectorType>(I->getInitializer()->getType())) {
2023 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
2024 // As with structs and vectors, but with an extra set of braces
2025 // because arrays are wrapped in structs.
2028 // Just print it out normally.
2029 writeOperand(I->getInitializer(), true);
2037 Out << "\n\n/* Function Bodies */\n";
2039 // Emit some helper functions for dealing with FCMP instruction's
2041 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2042 Out << "return X == X && Y == Y; }\n";
2043 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2044 Out << "return X != X || Y != Y; }\n";
2045 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
2046 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
2047 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
2048 Out << "return X != Y; }\n";
2049 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
2050 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
2051 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
2052 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
2053 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
2054 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
2055 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
2056 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
2057 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
2058 Out << "return X == Y ; }\n";
2059 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
2060 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
2061 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
2062 Out << "return X < Y ; }\n";
2063 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
2064 Out << "return X > Y ; }\n";
2065 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
2066 Out << "return X <= Y ; }\n";
2067 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
2068 Out << "return X >= Y ; }\n";
2073 /// Output all floating point constants that cannot be printed accurately...
2074 void CWriter::printFloatingPointConstants(Function &F) {
2075 // Scan the module for floating point constants. If any FP constant is used
2076 // in the function, we want to redirect it here so that we do not depend on
2077 // the precision of the printed form, unless the printed form preserves
2080 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2082 printFloatingPointConstants(*I);
2087 void CWriter::printFloatingPointConstants(const Constant *C) {
2088 // If this is a constant expression, recursively check for constant fp values.
2089 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2090 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2091 printFloatingPointConstants(CE->getOperand(i));
2095 // Otherwise, check for a FP constant that we need to print.
2096 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2098 // Do not put in FPConstantMap if safe.
2099 isFPCSafeToPrint(FPC) ||
2100 // Already printed this constant?
2101 FPConstantMap.count(FPC))
2104 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2106 if (FPC->getType() == Type::DoubleTy) {
2107 double Val = FPC->getValueAPF().convertToDouble();
2108 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2109 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2110 << " = 0x" << utohexstr(i)
2111 << "ULL; /* " << Val << " */\n";
2112 } else if (FPC->getType() == Type::FloatTy) {
2113 float Val = FPC->getValueAPF().convertToFloat();
2114 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2116 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2117 << " = 0x" << utohexstr(i)
2118 << "U; /* " << Val << " */\n";
2119 } else if (FPC->getType() == Type::X86_FP80Ty) {
2120 // api needed to prevent premature destruction
2121 APInt api = FPC->getValueAPF().bitcastToAPInt();
2122 const uint64_t *p = api.getRawData();
2123 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
2124 << " = { 0x" << utohexstr(p[0])
2125 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
2126 << "}; /* Long double constant */\n";
2127 } else if (FPC->getType() == Type::PPC_FP128Ty) {
2128 APInt api = FPC->getValueAPF().bitcastToAPInt();
2129 const uint64_t *p = api.getRawData();
2130 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2132 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2133 << "}; /* Long double constant */\n";
2136 llvm_unreachable("Unknown float type!");
2142 /// printSymbolTable - Run through symbol table looking for type names. If a
2143 /// type name is found, emit its declaration...
2145 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
2146 Out << "/* Helper union for bitcasts */\n";
2147 Out << "typedef union {\n";
2148 Out << " unsigned int Int32;\n";
2149 Out << " unsigned long long Int64;\n";
2150 Out << " float Float;\n";
2151 Out << " double Double;\n";
2152 Out << "} llvmBitCastUnion;\n";
2154 // We are only interested in the type plane of the symbol table.
2155 TypeSymbolTable::const_iterator I = TST.begin();
2156 TypeSymbolTable::const_iterator End = TST.end();
2158 // If there are no type names, exit early.
2159 if (I == End) return;
2161 // Print out forward declarations for structure types before anything else!
2162 Out << "/* Structure forward decls */\n";
2163 for (; I != End; ++I) {
2164 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
2165 Out << Name << ";\n";
2166 TypeNames.insert(std::make_pair(I->second, Name));
2171 // Now we can print out typedefs. Above, we guaranteed that this can only be
2172 // for struct or opaque types.
2173 Out << "/* Typedefs */\n";
2174 for (I = TST.begin(); I != End; ++I) {
2175 std::string Name = "l_" + Mang->makeNameProper(I->first);
2177 printType(Out, I->second, false, Name);
2183 // Keep track of which structures have been printed so far...
2184 std::set<const Type *> StructPrinted;
2186 // Loop over all structures then push them into the stack so they are
2187 // printed in the correct order.
2189 Out << "/* Structure contents */\n";
2190 for (I = TST.begin(); I != End; ++I)
2191 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
2192 // Only print out used types!
2193 printContainedStructs(I->second, StructPrinted);
2196 // Push the struct onto the stack and recursively push all structs
2197 // this one depends on.
2199 // TODO: Make this work properly with vector types
2201 void CWriter::printContainedStructs(const Type *Ty,
2202 std::set<const Type*> &StructPrinted) {
2203 // Don't walk through pointers.
2204 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
2206 // Print all contained types first.
2207 for (Type::subtype_iterator I = Ty->subtype_begin(),
2208 E = Ty->subtype_end(); I != E; ++I)
2209 printContainedStructs(*I, StructPrinted);
2211 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
2212 // Check to see if we have already printed this struct.
2213 if (StructPrinted.insert(Ty).second) {
2214 // Print structure type out.
2215 std::string Name = TypeNames[Ty];
2216 printType(Out, Ty, false, Name, true);
2222 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
2223 /// isStructReturn - Should this function actually return a struct by-value?
2224 bool isStructReturn = F->hasStructRetAttr();
2226 if (F->hasLocalLinkage()) Out << "static ";
2227 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2228 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
2229 switch (F->getCallingConv()) {
2230 case CallingConv::X86_StdCall:
2231 Out << "__attribute__((stdcall)) ";
2233 case CallingConv::X86_FastCall:
2234 Out << "__attribute__((fastcall)) ";
2238 // Loop over the arguments, printing them...
2239 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
2240 const AttrListPtr &PAL = F->getAttributes();
2242 std::stringstream FunctionInnards;
2244 // Print out the name...
2245 FunctionInnards << GetValueName(F) << '(';
2247 bool PrintedArg = false;
2248 if (!F->isDeclaration()) {
2249 if (!F->arg_empty()) {
2250 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2253 // If this is a struct-return function, don't print the hidden
2254 // struct-return argument.
2255 if (isStructReturn) {
2256 assert(I != E && "Invalid struct return function!");
2261 std::string ArgName;
2262 for (; I != E; ++I) {
2263 if (PrintedArg) FunctionInnards << ", ";
2264 if (I->hasName() || !Prototype)
2265 ArgName = GetValueName(I);
2268 const Type *ArgTy = I->getType();
2269 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2270 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2271 ByValParams.insert(I);
2273 printType(FunctionInnards, ArgTy,
2274 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
2281 // Loop over the arguments, printing them.
2282 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
2285 // If this is a struct-return function, don't print the hidden
2286 // struct-return argument.
2287 if (isStructReturn) {
2288 assert(I != E && "Invalid struct return function!");
2293 for (; I != E; ++I) {
2294 if (PrintedArg) FunctionInnards << ", ";
2295 const Type *ArgTy = *I;
2296 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2297 assert(isa<PointerType>(ArgTy));
2298 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2300 printType(FunctionInnards, ArgTy,
2301 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
2307 // Finish printing arguments... if this is a vararg function, print the ...,
2308 // unless there are no known types, in which case, we just emit ().
2310 if (FT->isVarArg() && PrintedArg) {
2311 if (PrintedArg) FunctionInnards << ", ";
2312 FunctionInnards << "..."; // Output varargs portion of signature!
2313 } else if (!FT->isVarArg() && !PrintedArg) {
2314 FunctionInnards << "void"; // ret() -> ret(void) in C.
2316 FunctionInnards << ')';
2318 // Get the return tpe for the function.
2320 if (!isStructReturn)
2321 RetTy = F->getReturnType();
2323 // If this is a struct-return function, print the struct-return type.
2324 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2327 // Print out the return type and the signature built above.
2328 printType(Out, RetTy,
2329 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
2330 FunctionInnards.str());
2333 static inline bool isFPIntBitCast(const Instruction &I) {
2334 if (!isa<BitCastInst>(I))
2336 const Type *SrcTy = I.getOperand(0)->getType();
2337 const Type *DstTy = I.getType();
2338 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2339 (DstTy->isFloatingPoint() && SrcTy->isInteger());
2342 void CWriter::printFunction(Function &F) {
2343 /// isStructReturn - Should this function actually return a struct by-value?
2344 bool isStructReturn = F.hasStructRetAttr();
2346 printFunctionSignature(&F, false);
2349 // If this is a struct return function, handle the result with magic.
2350 if (isStructReturn) {
2351 const Type *StructTy =
2352 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2354 printType(Out, StructTy, false, "StructReturn");
2355 Out << "; /* Struct return temporary */\n";
2358 printType(Out, F.arg_begin()->getType(), false,
2359 GetValueName(F.arg_begin()));
2360 Out << " = &StructReturn;\n";
2363 bool PrintedVar = false;
2365 // print local variable information for the function
2366 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2367 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2369 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2370 Out << "; /* Address-exposed local */\n";
2372 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
2374 printType(Out, I->getType(), false, GetValueName(&*I));
2377 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2379 printType(Out, I->getType(), false,
2380 GetValueName(&*I)+"__PHI_TEMPORARY");
2385 // We need a temporary for the BitCast to use so it can pluck a value out
2386 // of a union to do the BitCast. This is separate from the need for a
2387 // variable to hold the result of the BitCast.
2388 if (isFPIntBitCast(*I)) {
2389 Out << " llvmBitCastUnion " << GetValueName(&*I)
2390 << "__BITCAST_TEMPORARY;\n";
2398 if (F.hasExternalLinkage() && F.getName() == "main")
2399 Out << " CODE_FOR_MAIN();\n";
2401 // print the basic blocks
2402 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2403 if (Loop *L = LI->getLoopFor(BB)) {
2404 if (L->getHeader() == BB && L->getParentLoop() == 0)
2407 printBasicBlock(BB);
2414 void CWriter::printLoop(Loop *L) {
2415 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2416 << "' to make GCC happy */\n";
2417 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2418 BasicBlock *BB = L->getBlocks()[i];
2419 Loop *BBLoop = LI->getLoopFor(BB);
2421 printBasicBlock(BB);
2422 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2425 Out << " } while (1); /* end of syntactic loop '"
2426 << L->getHeader()->getName() << "' */\n";
2429 void CWriter::printBasicBlock(BasicBlock *BB) {
2431 // Don't print the label for the basic block if there are no uses, or if
2432 // the only terminator use is the predecessor basic block's terminator.
2433 // We have to scan the use list because PHI nodes use basic blocks too but
2434 // do not require a label to be generated.
2436 bool NeedsLabel = false;
2437 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2438 if (isGotoCodeNecessary(*PI, BB)) {
2443 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2445 // Output all of the instructions in the basic block...
2446 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2448 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2449 if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
2453 writeInstComputationInline(*II);
2458 // Don't emit prefix or suffix for the terminator.
2459 visit(*BB->getTerminator());
2463 // Specific Instruction type classes... note that all of the casts are
2464 // necessary because we use the instruction classes as opaque types...
2466 void CWriter::visitReturnInst(ReturnInst &I) {
2467 // If this is a struct return function, return the temporary struct.
2468 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
2470 if (isStructReturn) {
2471 Out << " return StructReturn;\n";
2475 // Don't output a void return if this is the last basic block in the function
2476 if (I.getNumOperands() == 0 &&
2477 &*--I.getParent()->getParent()->end() == I.getParent() &&
2478 !I.getParent()->size() == 1) {
2482 if (I.getNumOperands() > 1) {
2485 printType(Out, I.getParent()->getParent()->getReturnType());
2486 Out << " llvm_cbe_mrv_temp = {\n";
2487 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2489 writeOperand(I.getOperand(i));
2495 Out << " return llvm_cbe_mrv_temp;\n";
2501 if (I.getNumOperands()) {
2503 writeOperand(I.getOperand(0));
2508 void CWriter::visitSwitchInst(SwitchInst &SI) {
2511 writeOperand(SI.getOperand(0));
2512 Out << ") {\n default:\n";
2513 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2514 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2516 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2518 writeOperand(SI.getOperand(i));
2520 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2521 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2522 printBranchToBlock(SI.getParent(), Succ, 2);
2523 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
2529 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2530 Out << " /*UNREACHABLE*/;\n";
2533 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2534 /// FIXME: This should be reenabled, but loop reordering safe!!
2537 if (next(Function::iterator(From)) != Function::iterator(To))
2538 return true; // Not the direct successor, we need a goto.
2540 //isa<SwitchInst>(From->getTerminator())
2542 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2547 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2548 BasicBlock *Successor,
2550 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2551 PHINode *PN = cast<PHINode>(I);
2552 // Now we have to do the printing.
2553 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2554 if (!isa<UndefValue>(IV)) {
2555 Out << std::string(Indent, ' ');
2556 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2558 Out << "; /* for PHI node */\n";
2563 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2565 if (isGotoCodeNecessary(CurBB, Succ)) {
2566 Out << std::string(Indent, ' ') << " goto ";
2572 // Branch instruction printing - Avoid printing out a branch to a basic block
2573 // that immediately succeeds the current one.
2575 void CWriter::visitBranchInst(BranchInst &I) {
2577 if (I.isConditional()) {
2578 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2580 writeOperand(I.getCondition());
2583 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2584 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2586 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2587 Out << " } else {\n";
2588 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2589 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2592 // First goto not necessary, assume second one is...
2594 writeOperand(I.getCondition());
2597 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2598 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2603 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2604 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2609 // PHI nodes get copied into temporary values at the end of predecessor basic
2610 // blocks. We now need to copy these temporary values into the REAL value for
2612 void CWriter::visitPHINode(PHINode &I) {
2614 Out << "__PHI_TEMPORARY";
2618 void CWriter::visitBinaryOperator(Instruction &I) {
2619 // binary instructions, shift instructions, setCond instructions.
2620 assert(!isa<PointerType>(I.getType()));
2622 // We must cast the results of binary operations which might be promoted.
2623 bool needsCast = false;
2624 if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty)
2625 || (I.getType() == Type::FloatTy)) {
2628 printType(Out, I.getType(), false);
2632 // If this is a negation operation, print it out as such. For FP, we don't
2633 // want to print "-0.0 - X".
2634 if (BinaryOperator::isNeg(&I)) {
2636 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2638 } else if (BinaryOperator::isFNeg(&I)) {
2640 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2642 } else if (I.getOpcode() == Instruction::FRem) {
2643 // Output a call to fmod/fmodf instead of emitting a%b
2644 if (I.getType() == Type::FloatTy)
2646 else if (I.getType() == Type::DoubleTy)
2648 else // all 3 flavors of long double
2650 writeOperand(I.getOperand(0));
2652 writeOperand(I.getOperand(1));
2656 // Write out the cast of the instruction's value back to the proper type
2658 bool NeedsClosingParens = writeInstructionCast(I);
2660 // Certain instructions require the operand to be forced to a specific type
2661 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2662 // below for operand 1
2663 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2665 switch (I.getOpcode()) {
2666 case Instruction::Add:
2667 case Instruction::FAdd: Out << " + "; break;
2668 case Instruction::Sub:
2669 case Instruction::FSub: Out << " - "; break;
2670 case Instruction::Mul:
2671 case Instruction::FMul: Out << " * "; break;
2672 case Instruction::URem:
2673 case Instruction::SRem:
2674 case Instruction::FRem: Out << " % "; break;
2675 case Instruction::UDiv:
2676 case Instruction::SDiv:
2677 case Instruction::FDiv: Out << " / "; break;
2678 case Instruction::And: Out << " & "; break;
2679 case Instruction::Or: Out << " | "; break;
2680 case Instruction::Xor: Out << " ^ "; break;
2681 case Instruction::Shl : Out << " << "; break;
2682 case Instruction::LShr:
2683 case Instruction::AShr: Out << " >> "; break;
2686 cerr << "Invalid operator type!" << I;
2688 llvm_unreachable(0);
2691 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2692 if (NeedsClosingParens)
2701 void CWriter::visitICmpInst(ICmpInst &I) {
2702 // We must cast the results of icmp which might be promoted.
2703 bool needsCast = false;
2705 // Write out the cast of the instruction's value back to the proper type
2707 bool NeedsClosingParens = writeInstructionCast(I);
2709 // Certain icmp predicate require the operand to be forced to a specific type
2710 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2711 // below for operand 1
2712 writeOperandWithCast(I.getOperand(0), I);
2714 switch (I.getPredicate()) {
2715 case ICmpInst::ICMP_EQ: Out << " == "; break;
2716 case ICmpInst::ICMP_NE: Out << " != "; break;
2717 case ICmpInst::ICMP_ULE:
2718 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2719 case ICmpInst::ICMP_UGE:
2720 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2721 case ICmpInst::ICMP_ULT:
2722 case ICmpInst::ICMP_SLT: Out << " < "; break;
2723 case ICmpInst::ICMP_UGT:
2724 case ICmpInst::ICMP_SGT: Out << " > "; break;
2727 cerr << "Invalid icmp predicate!" << I;
2729 llvm_unreachable(0);
2732 writeOperandWithCast(I.getOperand(1), I);
2733 if (NeedsClosingParens)
2741 void CWriter::visitFCmpInst(FCmpInst &I) {
2742 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2746 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2752 switch (I.getPredicate()) {
2753 default: llvm_unreachable("Illegal FCmp predicate");
2754 case FCmpInst::FCMP_ORD: op = "ord"; break;
2755 case FCmpInst::FCMP_UNO: op = "uno"; break;
2756 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2757 case FCmpInst::FCMP_UNE: op = "une"; break;
2758 case FCmpInst::FCMP_ULT: op = "ult"; break;
2759 case FCmpInst::FCMP_ULE: op = "ule"; break;
2760 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2761 case FCmpInst::FCMP_UGE: op = "uge"; break;
2762 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2763 case FCmpInst::FCMP_ONE: op = "one"; break;
2764 case FCmpInst::FCMP_OLT: op = "olt"; break;
2765 case FCmpInst::FCMP_OLE: op = "ole"; break;
2766 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2767 case FCmpInst::FCMP_OGE: op = "oge"; break;
2770 Out << "llvm_fcmp_" << op << "(";
2771 // Write the first operand
2772 writeOperand(I.getOperand(0));
2774 // Write the second operand
2775 writeOperand(I.getOperand(1));
2779 static const char * getFloatBitCastField(const Type *Ty) {
2780 switch (Ty->getTypeID()) {
2781 default: llvm_unreachable("Invalid Type");
2782 case Type::FloatTyID: return "Float";
2783 case Type::DoubleTyID: return "Double";
2784 case Type::IntegerTyID: {
2785 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2794 void CWriter::visitCastInst(CastInst &I) {
2795 const Type *DstTy = I.getType();
2796 const Type *SrcTy = I.getOperand(0)->getType();
2797 if (isFPIntBitCast(I)) {
2799 // These int<->float and long<->double casts need to be handled specially
2800 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2801 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2802 writeOperand(I.getOperand(0));
2803 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2804 << getFloatBitCastField(I.getType());
2810 printCast(I.getOpcode(), SrcTy, DstTy);
2812 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
2813 if (SrcTy == Type::Int1Ty && I.getOpcode() == Instruction::SExt)
2816 writeOperand(I.getOperand(0));
2818 if (DstTy == Type::Int1Ty &&
2819 (I.getOpcode() == Instruction::Trunc ||
2820 I.getOpcode() == Instruction::FPToUI ||
2821 I.getOpcode() == Instruction::FPToSI ||
2822 I.getOpcode() == Instruction::PtrToInt)) {
2823 // Make sure we really get a trunc to bool by anding the operand with 1
2829 void CWriter::visitSelectInst(SelectInst &I) {
2831 writeOperand(I.getCondition());
2833 writeOperand(I.getTrueValue());
2835 writeOperand(I.getFalseValue());
2840 void CWriter::lowerIntrinsics(Function &F) {
2841 // This is used to keep track of intrinsics that get generated to a lowered
2842 // function. We must generate the prototypes before the function body which
2843 // will only be expanded on first use (by the loop below).
2844 std::vector<Function*> prototypesToGen;
2846 // Examine all the instructions in this function to find the intrinsics that
2847 // need to be lowered.
2848 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2849 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2850 if (CallInst *CI = dyn_cast<CallInst>(I++))
2851 if (Function *F = CI->getCalledFunction())
2852 switch (F->getIntrinsicID()) {
2853 case Intrinsic::not_intrinsic:
2854 case Intrinsic::memory_barrier:
2855 case Intrinsic::vastart:
2856 case Intrinsic::vacopy:
2857 case Intrinsic::vaend:
2858 case Intrinsic::returnaddress:
2859 case Intrinsic::frameaddress:
2860 case Intrinsic::setjmp:
2861 case Intrinsic::longjmp:
2862 case Intrinsic::prefetch:
2863 case Intrinsic::dbg_stoppoint:
2864 case Intrinsic::powi:
2865 case Intrinsic::x86_sse_cmp_ss:
2866 case Intrinsic::x86_sse_cmp_ps:
2867 case Intrinsic::x86_sse2_cmp_sd:
2868 case Intrinsic::x86_sse2_cmp_pd:
2869 case Intrinsic::ppc_altivec_lvsl:
2870 // We directly implement these intrinsics
2873 // If this is an intrinsic that directly corresponds to a GCC
2874 // builtin, we handle it.
2875 const char *BuiltinName = "";
2876 #define GET_GCC_BUILTIN_NAME
2877 #include "llvm/Intrinsics.gen"
2878 #undef GET_GCC_BUILTIN_NAME
2879 // If we handle it, don't lower it.
2880 if (BuiltinName[0]) break;
2882 // All other intrinsic calls we must lower.
2883 Instruction *Before = 0;
2884 if (CI != &BB->front())
2885 Before = prior(BasicBlock::iterator(CI));
2887 IL->LowerIntrinsicCall(CI);
2888 if (Before) { // Move iterator to instruction after call
2893 // If the intrinsic got lowered to another call, and that call has
2894 // a definition then we need to make sure its prototype is emitted
2895 // before any calls to it.
2896 if (CallInst *Call = dyn_cast<CallInst>(I))
2897 if (Function *NewF = Call->getCalledFunction())
2898 if (!NewF->isDeclaration())
2899 prototypesToGen.push_back(NewF);
2904 // We may have collected some prototypes to emit in the loop above.
2905 // Emit them now, before the function that uses them is emitted. But,
2906 // be careful not to emit them twice.
2907 std::vector<Function*>::iterator I = prototypesToGen.begin();
2908 std::vector<Function*>::iterator E = prototypesToGen.end();
2909 for ( ; I != E; ++I) {
2910 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2912 printFunctionSignature(*I, true);
2918 void CWriter::visitCallInst(CallInst &I) {
2919 if (isa<InlineAsm>(I.getOperand(0)))
2920 return visitInlineAsm(I);
2922 bool WroteCallee = false;
2924 // Handle intrinsic function calls first...
2925 if (Function *F = I.getCalledFunction())
2926 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2927 if (visitBuiltinCall(I, ID, WroteCallee))
2930 Value *Callee = I.getCalledValue();
2932 const PointerType *PTy = cast<PointerType>(Callee->getType());
2933 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2935 // If this is a call to a struct-return function, assign to the first
2936 // parameter instead of passing it to the call.
2937 const AttrListPtr &PAL = I.getAttributes();
2938 bool hasByVal = I.hasByValArgument();
2939 bool isStructRet = I.hasStructRetAttr();
2941 writeOperandDeref(I.getOperand(1));
2945 if (I.isTailCall()) Out << " /*tail*/ ";
2948 // If this is an indirect call to a struct return function, we need to cast
2949 // the pointer. Ditto for indirect calls with byval arguments.
2950 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
2952 // GCC is a real PITA. It does not permit codegening casts of functions to
2953 // function pointers if they are in a call (it generates a trap instruction
2954 // instead!). We work around this by inserting a cast to void* in between
2955 // the function and the function pointer cast. Unfortunately, we can't just
2956 // form the constant expression here, because the folder will immediately
2959 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2960 // that void* and function pointers have the same size. :( To deal with this
2961 // in the common case, we handle casts where the number of arguments passed
2964 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2966 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2972 // Ok, just cast the pointer type.
2975 printStructReturnPointerFunctionType(Out, PAL,
2976 cast<PointerType>(I.getCalledValue()->getType()));
2978 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
2980 printType(Out, I.getCalledValue()->getType());
2983 writeOperand(Callee);
2984 if (NeedsCast) Out << ')';
2989 unsigned NumDeclaredParams = FTy->getNumParams();
2991 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2993 if (isStructRet) { // Skip struct return argument.
2998 bool PrintedArg = false;
2999 for (; AI != AE; ++AI, ++ArgNo) {
3000 if (PrintedArg) Out << ", ";
3001 if (ArgNo < NumDeclaredParams &&
3002 (*AI)->getType() != FTy->getParamType(ArgNo)) {
3004 printType(Out, FTy->getParamType(ArgNo),
3005 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
3008 // Check if the argument is expected to be passed by value.
3009 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
3010 writeOperandDeref(*AI);
3018 /// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3019 /// if the entire call is handled, return false it it wasn't handled, and
3020 /// optionally set 'WroteCallee' if the callee has already been printed out.
3021 bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3022 bool &WroteCallee) {
3025 // If this is an intrinsic that directly corresponds to a GCC
3026 // builtin, we emit it here.
3027 const char *BuiltinName = "";
3028 Function *F = I.getCalledFunction();
3029 #define GET_GCC_BUILTIN_NAME
3030 #include "llvm/Intrinsics.gen"
3031 #undef GET_GCC_BUILTIN_NAME
3032 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3038 case Intrinsic::memory_barrier:
3039 Out << "__sync_synchronize()";
3041 case Intrinsic::vastart:
3044 Out << "va_start(*(va_list*)";
3045 writeOperand(I.getOperand(1));
3047 // Output the last argument to the enclosing function.
3048 if (I.getParent()->getParent()->arg_empty()) {
3050 raw_string_ostream Msg(msg);
3051 Msg << "The C backend does not currently support zero "
3052 << "argument varargs functions, such as '"
3053 << I.getParent()->getParent()->getName() << "'!";
3054 llvm_report_error(Msg.str());
3056 writeOperand(--I.getParent()->getParent()->arg_end());
3059 case Intrinsic::vaend:
3060 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3061 Out << "0; va_end(*(va_list*)";
3062 writeOperand(I.getOperand(1));
3065 Out << "va_end(*(va_list*)0)";
3068 case Intrinsic::vacopy:
3070 Out << "va_copy(*(va_list*)";
3071 writeOperand(I.getOperand(1));
3072 Out << ", *(va_list*)";
3073 writeOperand(I.getOperand(2));
3076 case Intrinsic::returnaddress:
3077 Out << "__builtin_return_address(";
3078 writeOperand(I.getOperand(1));
3081 case Intrinsic::frameaddress:
3082 Out << "__builtin_frame_address(";
3083 writeOperand(I.getOperand(1));
3086 case Intrinsic::powi:
3087 Out << "__builtin_powi(";
3088 writeOperand(I.getOperand(1));
3090 writeOperand(I.getOperand(2));
3093 case Intrinsic::setjmp:
3094 Out << "setjmp(*(jmp_buf*)";
3095 writeOperand(I.getOperand(1));
3098 case Intrinsic::longjmp:
3099 Out << "longjmp(*(jmp_buf*)";
3100 writeOperand(I.getOperand(1));
3102 writeOperand(I.getOperand(2));
3105 case Intrinsic::prefetch:
3106 Out << "LLVM_PREFETCH((const void *)";
3107 writeOperand(I.getOperand(1));
3109 writeOperand(I.getOperand(2));
3111 writeOperand(I.getOperand(3));
3114 case Intrinsic::stacksave:
3115 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3116 // to work around GCC bugs (see PR1809).
3117 Out << "0; *((void**)&" << GetValueName(&I)
3118 << ") = __builtin_stack_save()";
3120 case Intrinsic::dbg_stoppoint: {
3121 // If we use writeOperand directly we get a "u" suffix which is rejected
3123 std::stringstream SPIStr;
3124 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3125 SPI.getDirectory()->print(SPIStr);
3129 Out << SPIStr.str();
3131 SPI.getFileName()->print(SPIStr);
3132 Out << SPIStr.str() << "\"\n";
3135 case Intrinsic::x86_sse_cmp_ss:
3136 case Intrinsic::x86_sse_cmp_ps:
3137 case Intrinsic::x86_sse2_cmp_sd:
3138 case Intrinsic::x86_sse2_cmp_pd:
3140 printType(Out, I.getType());
3142 // Multiple GCC builtins multiplex onto this intrinsic.
3143 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
3144 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
3145 case 0: Out << "__builtin_ia32_cmpeq"; break;
3146 case 1: Out << "__builtin_ia32_cmplt"; break;
3147 case 2: Out << "__builtin_ia32_cmple"; break;
3148 case 3: Out << "__builtin_ia32_cmpunord"; break;
3149 case 4: Out << "__builtin_ia32_cmpneq"; break;
3150 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3151 case 6: Out << "__builtin_ia32_cmpnle"; break;
3152 case 7: Out << "__builtin_ia32_cmpord"; break;
3154 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3158 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3164 writeOperand(I.getOperand(1));
3166 writeOperand(I.getOperand(2));
3169 case Intrinsic::ppc_altivec_lvsl:
3171 printType(Out, I.getType());
3173 Out << "__builtin_altivec_lvsl(0, (void*)";
3174 writeOperand(I.getOperand(1));
3180 //This converts the llvm constraint string to something gcc is expecting.
3181 //TODO: work out platform independent constraints and factor those out
3182 // of the per target tables
3183 // handle multiple constraint codes
3184 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
3186 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3188 const char *const *table = 0;
3190 //Grab the translation table from TargetAsmInfo if it exists
3193 const TargetMachineRegistry::entry* Match =
3194 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
3196 //Per platform Target Machines don't exist, so create it
3197 // this must be done only once
3198 const TargetMachine* TM = Match->CtorFn(*TheModule, "");
3199 TAsm = TM->getTargetAsmInfo();
3203 table = TAsm->getAsmCBE();
3205 //Search the translation table if it exists
3206 for (int i = 0; table && table[i]; i += 2)
3207 if (c.Codes[0] == table[i])
3210 //default is identity
3214 //TODO: import logic from AsmPrinter.cpp
3215 static std::string gccifyAsm(std::string asmstr) {
3216 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3217 if (asmstr[i] == '\n')
3218 asmstr.replace(i, 1, "\\n");
3219 else if (asmstr[i] == '\t')
3220 asmstr.replace(i, 1, "\\t");
3221 else if (asmstr[i] == '$') {
3222 if (asmstr[i + 1] == '{') {
3223 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3224 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3225 std::string n = "%" +
3226 asmstr.substr(a + 1, b - a - 1) +
3227 asmstr.substr(i + 2, a - i - 2);
3228 asmstr.replace(i, b - i + 1, n);
3231 asmstr.replace(i, 1, "%");
3233 else if (asmstr[i] == '%')//grr
3234 { asmstr.replace(i, 1, "%%"); ++i;}
3239 //TODO: assumptions about what consume arguments from the call are likely wrong
3240 // handle communitivity
3241 void CWriter::visitInlineAsm(CallInst &CI) {
3242 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
3243 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
3245 std::vector<std::pair<Value*, int> > ResultVals;
3246 if (CI.getType() == Type::VoidTy)
3248 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3249 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3250 ResultVals.push_back(std::make_pair(&CI, (int)i));
3252 ResultVals.push_back(std::make_pair(&CI, -1));
3255 // Fix up the asm string for gcc and emit it.
3256 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3259 unsigned ValueCount = 0;
3260 bool IsFirst = true;
3262 // Convert over all the output constraints.
3263 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3264 E = Constraints.end(); I != E; ++I) {
3266 if (I->Type != InlineAsm::isOutput) {
3268 continue; // Ignore non-output constraints.
3271 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3272 std::string C = InterpretASMConstraint(*I);
3273 if (C.empty()) continue;
3284 if (ValueCount < ResultVals.size()) {
3285 DestVal = ResultVals[ValueCount].first;
3286 DestValNo = ResultVals[ValueCount].second;
3288 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3290 if (I->isEarlyClobber)
3293 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3294 if (DestValNo != -1)
3295 Out << ".field" << DestValNo; // Multiple retvals.
3301 // Convert over all the input constraints.
3305 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3306 E = Constraints.end(); I != E; ++I) {
3307 if (I->Type != InlineAsm::isInput) {
3309 continue; // Ignore non-input constraints.
3312 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3313 std::string C = InterpretASMConstraint(*I);
3314 if (C.empty()) continue;
3321 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3322 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3324 Out << "\"" << C << "\"(";
3326 writeOperand(SrcVal);
3328 writeOperandDeref(SrcVal);
3332 // Convert over the clobber constraints.
3335 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3336 E = Constraints.end(); I != E; ++I) {
3337 if (I->Type != InlineAsm::isClobber)
3338 continue; // Ignore non-input constraints.
3340 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3341 std::string C = InterpretASMConstraint(*I);
3342 if (C.empty()) continue;
3349 Out << '\"' << C << '"';
3355 void CWriter::visitMallocInst(MallocInst &I) {
3356 llvm_unreachable("lowerallocations pass didn't work!");
3359 void CWriter::visitAllocaInst(AllocaInst &I) {
3361 printType(Out, I.getType());
3362 Out << ") alloca(sizeof(";
3363 printType(Out, I.getType()->getElementType());
3365 if (I.isArrayAllocation()) {
3367 writeOperand(I.getOperand(0));
3372 void CWriter::visitFreeInst(FreeInst &I) {
3373 llvm_unreachable("lowerallocations pass didn't work!");
3376 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
3377 gep_type_iterator E, bool Static) {
3379 // If there are no indices, just print out the pointer.
3385 // Find out if the last index is into a vector. If so, we have to print this
3386 // specially. Since vectors can't have elements of indexable type, only the
3387 // last index could possibly be of a vector element.
3388 const VectorType *LastIndexIsVector = 0;
3390 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3391 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
3396 // If the last index is into a vector, we can't print it as &a[i][j] because
3397 // we can't index into a vector with j in GCC. Instead, emit this as
3398 // (((float*)&a[i])+j)
3399 if (LastIndexIsVector) {
3401 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3407 // If the first index is 0 (very typical) we can do a number of
3408 // simplifications to clean up the code.
3409 Value *FirstOp = I.getOperand();
3410 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3411 // First index isn't simple, print it the hard way.
3414 ++I; // Skip the zero index.
3416 // Okay, emit the first operand. If Ptr is something that is already address
3417 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3418 if (isAddressExposed(Ptr)) {
3419 writeOperandInternal(Ptr, Static);
3420 } else if (I != E && isa<StructType>(*I)) {
3421 // If we didn't already emit the first operand, see if we can print it as
3422 // P->f instead of "P[0].f"
3424 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3425 ++I; // eat the struct index as well.
3427 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3434 for (; I != E; ++I) {
3435 if (isa<StructType>(*I)) {
3436 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3437 } else if (isa<ArrayType>(*I)) {
3439 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3441 } else if (!isa<VectorType>(*I)) {
3443 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3446 // If the last index is into a vector, then print it out as "+j)". This
3447 // works with the 'LastIndexIsVector' code above.
3448 if (isa<Constant>(I.getOperand()) &&
3449 cast<Constant>(I.getOperand())->isNullValue()) {
3450 Out << "))"; // avoid "+0".
3453 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3461 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3462 bool IsVolatile, unsigned Alignment) {
3464 bool IsUnaligned = Alignment &&
3465 Alignment < TD->getABITypeAlignment(OperandType);
3469 if (IsVolatile || IsUnaligned) {
3472 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3473 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3476 if (IsVolatile) Out << "volatile ";
3482 writeOperand(Operand);
3484 if (IsVolatile || IsUnaligned) {
3491 void CWriter::visitLoadInst(LoadInst &I) {
3492 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3497 void CWriter::visitStoreInst(StoreInst &I) {
3498 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3499 I.isVolatile(), I.getAlignment());
3501 Value *Operand = I.getOperand(0);
3502 Constant *BitMask = 0;
3503 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3504 if (!ITy->isPowerOf2ByteWidth())
3505 // We have a bit width that doesn't match an even power-of-2 byte
3506 // size. Consequently we must & the value with the type's bit mask
3507 BitMask = Context->getConstantInt(ITy, ITy->getBitMask());
3510 writeOperand(Operand);
3513 printConstant(BitMask, false);
3518 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
3519 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
3520 gep_type_end(I), false);
3523 void CWriter::visitVAArgInst(VAArgInst &I) {
3524 Out << "va_arg(*(va_list*)";
3525 writeOperand(I.getOperand(0));
3527 printType(Out, I.getType());
3531 void CWriter::visitInsertElementInst(InsertElementInst &I) {
3532 const Type *EltTy = I.getType()->getElementType();
3533 writeOperand(I.getOperand(0));
3536 printType(Out, PointerType::getUnqual(EltTy));
3537 Out << ")(&" << GetValueName(&I) << "))[";
3538 writeOperand(I.getOperand(2));
3540 writeOperand(I.getOperand(1));
3544 void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3545 // We know that our operand is not inlined.
3548 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3549 printType(Out, PointerType::getUnqual(EltTy));
3550 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3551 writeOperand(I.getOperand(1));
3555 void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3557 printType(Out, SVI.getType());
3559 const VectorType *VT = SVI.getType();
3560 unsigned NumElts = VT->getNumElements();
3561 const Type *EltTy = VT->getElementType();
3563 for (unsigned i = 0; i != NumElts; ++i) {
3565 int SrcVal = SVI.getMaskValue(i);
3566 if ((unsigned)SrcVal >= NumElts*2) {
3567 Out << " 0/*undef*/ ";
3569 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3570 if (isa<Instruction>(Op)) {
3571 // Do an extractelement of this value from the appropriate input.
3573 printType(Out, PointerType::getUnqual(EltTy));
3574 Out << ")(&" << GetValueName(Op)
3575 << "))[" << (SrcVal & (NumElts-1)) << "]";
3576 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3579 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
3588 void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3589 // Start by copying the entire aggregate value into the result variable.
3590 writeOperand(IVI.getOperand(0));
3593 // Then do the insert to update the field.
3594 Out << GetValueName(&IVI);
3595 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3597 const Type *IndexedTy =
3598 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3599 if (isa<ArrayType>(IndexedTy))
3600 Out << ".array[" << *i << "]";
3602 Out << ".field" << *i;
3605 writeOperand(IVI.getOperand(1));
3608 void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3610 if (isa<UndefValue>(EVI.getOperand(0))) {
3612 printType(Out, EVI.getType());
3613 Out << ") 0/*UNDEF*/";
3615 Out << GetValueName(EVI.getOperand(0));
3616 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3618 const Type *IndexedTy =
3619 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3620 if (isa<ArrayType>(IndexedTy))
3621 Out << ".array[" << *i << "]";
3623 Out << ".field" << *i;
3629 //===----------------------------------------------------------------------===//
3630 // External Interface declaration
3631 //===----------------------------------------------------------------------===//
3633 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
3634 formatted_raw_ostream &o,
3635 CodeGenFileType FileType,
3636 CodeGenOpt::Level OptLevel) {
3637 if (FileType != TargetMachine::AssemblyFile) return true;
3639 PM.add(createGCLoweringPass());
3640 PM.add(createLowerAllocationsPass(true));
3641 PM.add(createLowerInvokePass());
3642 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3643 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3644 PM.add(new CWriter(o));
3645 PM.add(createGCInfoDeleter());