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/GetElementPtrTypeIterator.h"
39 #include "llvm/Support/InstVisitor.h"
40 #include "llvm/Support/Mangler.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Config/config.h"
51 // Register the target.
52 static RegisterTarget<CTargetMachine> X("c", " C backend");
55 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
56 /// any unnamed structure types that are used by the program, and merges
57 /// external functions with the same name.
59 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
62 CBackendNameAllUsedStructsAndMergeFunctions()
63 : ModulePass((intptr_t)&ID) {}
64 void getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.addRequired<FindUsedTypes>();
68 virtual const char *getPassName() const {
69 return "C backend type canonicalizer";
72 virtual bool runOnModule(Module &M);
75 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
77 /// CWriter - This class is the main chunk of code that converts an LLVM
78 /// module to a C translation unit.
79 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
81 IntrinsicLowering *IL;
84 const Module *TheModule;
85 const TargetAsmInfo* TAsm;
87 std::map<const Type *, std::string> TypeNames;
88 std::map<const ConstantFP *, unsigned> FPConstantMap;
89 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
90 std::set<const Argument*> ByValParams;
94 explicit CWriter(raw_ostream &o)
95 : FunctionPass((intptr_t)&ID), Out(o), IL(0), Mang(0), LI(0),
96 TheModule(0), TAsm(0), TD(0) {}
98 virtual const char *getPassName() const { return "C backend"; }
100 void getAnalysisUsage(AnalysisUsage &AU) const {
101 AU.addRequired<LoopInfo>();
102 AU.setPreservesAll();
105 virtual bool doInitialization(Module &M);
107 bool runOnFunction(Function &F) {
108 LI = &getAnalysis<LoopInfo>();
110 // Get rid of intrinsics we can't handle.
113 // Output all floating point constants that cannot be printed accurately.
114 printFloatingPointConstants(F);
120 virtual bool doFinalization(Module &M) {
123 FPConstantMap.clear();
126 intrinsicPrototypesAlreadyGenerated.clear();
130 raw_ostream &printType(raw_ostream &Out, const Type *Ty,
131 bool isSigned = false,
132 const std::string &VariableName = "",
133 bool IgnoreName = false,
134 const PAListPtr &PAL = PAListPtr());
135 std::ostream &printType(std::ostream &Out, const Type *Ty,
136 bool isSigned = false,
137 const std::string &VariableName = "",
138 bool IgnoreName = false,
139 const PAListPtr &PAL = PAListPtr());
140 raw_ostream &printSimpleType(raw_ostream &Out, const Type *Ty,
142 const std::string &NameSoFar = "");
143 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
145 const std::string &NameSoFar = "");
147 void printStructReturnPointerFunctionType(raw_ostream &Out,
148 const PAListPtr &PAL,
149 const PointerType *Ty);
151 /// writeOperandDeref - Print the result of dereferencing the specified
152 /// operand with '*'. This is equivalent to printing '*' then using
153 /// writeOperand, but avoids excess syntax in some cases.
154 void writeOperandDeref(Value *Operand) {
155 if (isAddressExposed(Operand)) {
156 // Already something with an address exposed.
157 writeOperandInternal(Operand);
160 writeOperand(Operand);
165 void writeOperand(Value *Operand, bool Static = false);
166 void writeInstComputationInline(Instruction &I);
167 void writeOperandInternal(Value *Operand, bool Static = false);
168 void writeOperandWithCast(Value* Operand, unsigned Opcode);
169 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
170 bool writeInstructionCast(const Instruction &I);
172 void writeMemoryAccess(Value *Operand, const Type *OperandType,
173 bool IsVolatile, unsigned Alignment);
176 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
178 void lowerIntrinsics(Function &F);
180 void printModule(Module *M);
181 void printModuleTypes(const TypeSymbolTable &ST);
182 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
183 void printFloatingPointConstants(Function &F);
184 void printFunctionSignature(const Function *F, bool Prototype);
186 void printFunction(Function &);
187 void printBasicBlock(BasicBlock *BB);
188 void printLoop(Loop *L);
190 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
191 void printConstant(Constant *CPV, bool Static);
192 void printConstantWithCast(Constant *CPV, unsigned Opcode);
193 bool printConstExprCast(const ConstantExpr *CE, bool Static);
194 void printConstantArray(ConstantArray *CPA, bool Static);
195 void printConstantVector(ConstantVector *CV, bool Static);
197 /// isAddressExposed - Return true if the specified value's name needs to
198 /// have its address taken in order to get a C value of the correct type.
199 /// This happens for global variables, byval parameters, and direct allocas.
200 bool isAddressExposed(const Value *V) const {
201 if (const Argument *A = dyn_cast<Argument>(V))
202 return ByValParams.count(A);
203 return isa<GlobalVariable>(V) || isDirectAlloca(V);
206 // isInlinableInst - Attempt to inline instructions into their uses to build
207 // trees as much as possible. To do this, we have to consistently decide
208 // what is acceptable to inline, so that variable declarations don't get
209 // printed and an extra copy of the expr is not emitted.
211 static bool isInlinableInst(const Instruction &I) {
212 // Always inline cmp instructions, even if they are shared by multiple
213 // expressions. GCC generates horrible code if we don't.
217 // Must be an expression, must be used exactly once. If it is dead, we
218 // emit it inline where it would go.
219 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
220 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
221 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
222 isa<InsertValueInst>(I))
223 // Don't inline a load across a store or other bad things!
226 // Must not be used in inline asm, extractelement, or shufflevector.
228 const Instruction &User = cast<Instruction>(*I.use_back());
229 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
230 isa<ShuffleVectorInst>(User))
234 // Only inline instruction it if it's use is in the same BB as the inst.
235 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
238 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
239 // variables which are accessed with the & operator. This causes GCC to
240 // generate significantly better code than to emit alloca calls directly.
242 static const AllocaInst *isDirectAlloca(const Value *V) {
243 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
244 if (!AI) return false;
245 if (AI->isArrayAllocation())
246 return 0; // FIXME: we can also inline fixed size array allocas!
247 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
252 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
253 static bool isInlineAsm(const Instruction& I) {
254 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
259 // Instruction visitation functions
260 friend class InstVisitor<CWriter>;
262 void visitReturnInst(ReturnInst &I);
263 void visitBranchInst(BranchInst &I);
264 void visitSwitchInst(SwitchInst &I);
265 void visitInvokeInst(InvokeInst &I) {
266 assert(0 && "Lowerinvoke pass didn't work!");
269 void visitUnwindInst(UnwindInst &I) {
270 assert(0 && "Lowerinvoke pass didn't work!");
272 void visitUnreachableInst(UnreachableInst &I);
274 void visitPHINode(PHINode &I);
275 void visitBinaryOperator(Instruction &I);
276 void visitICmpInst(ICmpInst &I);
277 void visitFCmpInst(FCmpInst &I);
279 void visitCastInst (CastInst &I);
280 void visitSelectInst(SelectInst &I);
281 void visitCallInst (CallInst &I);
282 void visitInlineAsm(CallInst &I);
283 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
285 void visitMallocInst(MallocInst &I);
286 void visitAllocaInst(AllocaInst &I);
287 void visitFreeInst (FreeInst &I);
288 void visitLoadInst (LoadInst &I);
289 void visitStoreInst (StoreInst &I);
290 void visitGetElementPtrInst(GetElementPtrInst &I);
291 void visitVAArgInst (VAArgInst &I);
293 void visitInsertElementInst(InsertElementInst &I);
294 void visitExtractElementInst(ExtractElementInst &I);
295 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
297 void visitInsertValueInst(InsertValueInst &I);
298 void visitExtractValueInst(ExtractValueInst &I);
300 void visitInstruction(Instruction &I) {
301 cerr << "C Writer does not know about " << I;
305 void outputLValue(Instruction *I) {
306 Out << " " << GetValueName(I) << " = ";
309 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
310 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
311 BasicBlock *Successor, unsigned Indent);
312 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
314 void printGEPExpression(Value *Ptr, gep_type_iterator I,
315 gep_type_iterator E, bool Static);
317 std::string GetValueName(const Value *Operand);
321 char CWriter::ID = 0;
323 /// This method inserts names for any unnamed structure types that are used by
324 /// the program, and removes names from structure types that are not used by the
327 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
328 // Get a set of types that are used by the program...
329 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
331 // Loop over the module symbol table, removing types from UT that are
332 // already named, and removing names for types that are not used.
334 TypeSymbolTable &TST = M.getTypeSymbolTable();
335 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
337 TypeSymbolTable::iterator I = TI++;
339 // If this isn't a struct or array type, remove it from our set of types
340 // to name. This simplifies emission later.
341 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
342 !isa<ArrayType>(I->second)) {
345 // If this is not used, remove it from the symbol table.
346 std::set<const Type *>::iterator UTI = UT.find(I->second);
350 UT.erase(UTI); // Only keep one name for this type.
354 // UT now contains types that are not named. Loop over it, naming
357 bool Changed = false;
358 unsigned RenameCounter = 0;
359 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
361 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
362 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
368 // Loop over all external functions and globals. If we have two with
369 // identical names, merge them.
370 // FIXME: This code should disappear when we don't allow values with the same
371 // names when they have different types!
372 std::map<std::string, GlobalValue*> ExtSymbols;
373 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
375 if (GV->isDeclaration() && GV->hasName()) {
376 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
377 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
379 // Found a conflict, replace this global with the previous one.
380 GlobalValue *OldGV = X.first->second;
381 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
382 GV->eraseFromParent();
387 // Do the same for globals.
388 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
390 GlobalVariable *GV = I++;
391 if (GV->isDeclaration() && GV->hasName()) {
392 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
393 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
395 // Found a conflict, replace this global with the previous one.
396 GlobalValue *OldGV = X.first->second;
397 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
398 GV->eraseFromParent();
407 /// printStructReturnPointerFunctionType - This is like printType for a struct
408 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
409 /// print it as "Struct (*)(...)", for struct return functions.
410 void CWriter::printStructReturnPointerFunctionType(raw_ostream &Out,
411 const PAListPtr &PAL,
412 const PointerType *TheTy) {
413 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
414 std::stringstream FunctionInnards;
415 FunctionInnards << " (*) (";
416 bool PrintedType = false;
418 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
419 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
421 for (++I, ++Idx; I != E; ++I, ++Idx) {
423 FunctionInnards << ", ";
424 const Type *ArgTy = *I;
425 if (PAL.paramHasAttr(Idx, ParamAttr::ByVal)) {
426 assert(isa<PointerType>(ArgTy));
427 ArgTy = cast<PointerType>(ArgTy)->getElementType();
429 printType(FunctionInnards, ArgTy,
430 /*isSigned=*/PAL.paramHasAttr(Idx, ParamAttr::SExt), "");
433 if (FTy->isVarArg()) {
435 FunctionInnards << ", ...";
436 } else if (!PrintedType) {
437 FunctionInnards << "void";
439 FunctionInnards << ')';
440 std::string tstr = FunctionInnards.str();
441 printType(Out, RetTy,
442 /*isSigned=*/PAL.paramHasAttr(0, ParamAttr::SExt), tstr);
446 CWriter::printSimpleType(raw_ostream &Out, const Type *Ty, bool isSigned,
447 const std::string &NameSoFar) {
448 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
449 "Invalid type for printSimpleType");
450 switch (Ty->getTypeID()) {
451 case Type::VoidTyID: return Out << "void " << NameSoFar;
452 case Type::IntegerTyID: {
453 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
455 return Out << "bool " << NameSoFar;
456 else if (NumBits <= 8)
457 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
458 else if (NumBits <= 16)
459 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
460 else if (NumBits <= 32)
461 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
462 else if (NumBits <= 64)
463 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
465 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
466 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
469 case Type::FloatTyID: return Out << "float " << NameSoFar;
470 case Type::DoubleTyID: return Out << "double " << NameSoFar;
471 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
472 // present matches host 'long double'.
473 case Type::X86_FP80TyID:
474 case Type::PPC_FP128TyID:
475 case Type::FP128TyID: return Out << "long double " << NameSoFar;
477 case Type::VectorTyID: {
478 const VectorType *VTy = cast<VectorType>(Ty);
479 return printSimpleType(Out, VTy->getElementType(), isSigned,
480 " __attribute__((vector_size(" +
481 utostr(TD->getABITypeSize(VTy)) + " ))) " + NameSoFar);
485 cerr << "Unknown primitive type: " << *Ty << "\n";
491 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
492 const std::string &NameSoFar) {
493 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
494 "Invalid type for printSimpleType");
495 switch (Ty->getTypeID()) {
496 case Type::VoidTyID: return Out << "void " << NameSoFar;
497 case Type::IntegerTyID: {
498 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
500 return Out << "bool " << NameSoFar;
501 else if (NumBits <= 8)
502 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
503 else if (NumBits <= 16)
504 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
505 else if (NumBits <= 32)
506 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
507 else if (NumBits <= 64)
508 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
510 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
511 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
514 case Type::FloatTyID: return Out << "float " << NameSoFar;
515 case Type::DoubleTyID: return Out << "double " << NameSoFar;
516 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
517 // present matches host 'long double'.
518 case Type::X86_FP80TyID:
519 case Type::PPC_FP128TyID:
520 case Type::FP128TyID: return Out << "long double " << NameSoFar;
522 case Type::VectorTyID: {
523 const VectorType *VTy = cast<VectorType>(Ty);
524 return printSimpleType(Out, VTy->getElementType(), isSigned,
525 " __attribute__((vector_size(" +
526 utostr(TD->getABITypeSize(VTy)) + " ))) " + NameSoFar);
530 cerr << "Unknown primitive type: " << *Ty << "\n";
535 // Pass the Type* and the variable name and this prints out the variable
538 raw_ostream &CWriter::printType(raw_ostream &Out, const Type *Ty,
539 bool isSigned, const std::string &NameSoFar,
540 bool IgnoreName, const PAListPtr &PAL) {
541 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
542 printSimpleType(Out, Ty, isSigned, NameSoFar);
546 // Check to see if the type is named.
547 if (!IgnoreName || isa<OpaqueType>(Ty)) {
548 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
549 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
552 switch (Ty->getTypeID()) {
553 case Type::FunctionTyID: {
554 const FunctionType *FTy = cast<FunctionType>(Ty);
555 std::stringstream FunctionInnards;
556 FunctionInnards << " (" << NameSoFar << ") (";
558 for (FunctionType::param_iterator I = FTy->param_begin(),
559 E = FTy->param_end(); I != E; ++I) {
560 const Type *ArgTy = *I;
561 if (PAL.paramHasAttr(Idx, ParamAttr::ByVal)) {
562 assert(isa<PointerType>(ArgTy));
563 ArgTy = cast<PointerType>(ArgTy)->getElementType();
565 if (I != FTy->param_begin())
566 FunctionInnards << ", ";
567 printType(FunctionInnards, ArgTy,
568 /*isSigned=*/PAL.paramHasAttr(Idx, ParamAttr::SExt), "");
571 if (FTy->isVarArg()) {
572 if (FTy->getNumParams())
573 FunctionInnards << ", ...";
574 } else if (!FTy->getNumParams()) {
575 FunctionInnards << "void";
577 FunctionInnards << ')';
578 std::string tstr = FunctionInnards.str();
579 printType(Out, FTy->getReturnType(),
580 /*isSigned=*/PAL.paramHasAttr(0, ParamAttr::SExt), tstr);
583 case Type::StructTyID: {
584 const StructType *STy = cast<StructType>(Ty);
585 Out << NameSoFar + " {\n";
587 for (StructType::element_iterator I = STy->element_begin(),
588 E = STy->element_end(); I != E; ++I) {
590 printType(Out, *I, false, "field" + utostr(Idx++));
595 Out << " __attribute__ ((packed))";
599 case Type::PointerTyID: {
600 const PointerType *PTy = cast<PointerType>(Ty);
601 std::string ptrName = "*" + NameSoFar;
603 if (isa<ArrayType>(PTy->getElementType()) ||
604 isa<VectorType>(PTy->getElementType()))
605 ptrName = "(" + ptrName + ")";
608 // Must be a function ptr cast!
609 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
610 return printType(Out, PTy->getElementType(), false, ptrName);
613 case Type::ArrayTyID: {
614 const ArrayType *ATy = cast<ArrayType>(Ty);
615 unsigned NumElements = ATy->getNumElements();
616 if (NumElements == 0) NumElements = 1;
617 // Arrays are wrapped in structs to allow them to have normal
618 // value semantics (avoiding the array "decay").
619 Out << NameSoFar << " { ";
620 printType(Out, ATy->getElementType(), false,
621 "array[" + utostr(NumElements) + "]");
625 case Type::OpaqueTyID: {
626 static int Count = 0;
627 std::string TyName = "struct opaque_" + itostr(Count++);
628 assert(TypeNames.find(Ty) == TypeNames.end());
629 TypeNames[Ty] = TyName;
630 return Out << TyName << ' ' << NameSoFar;
633 assert(0 && "Unhandled case in getTypeProps!");
640 // Pass the Type* and the variable name and this prints out the variable
643 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
644 bool isSigned, const std::string &NameSoFar,
645 bool IgnoreName, const PAListPtr &PAL) {
646 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
647 printSimpleType(Out, Ty, isSigned, NameSoFar);
651 // Check to see if the type is named.
652 if (!IgnoreName || isa<OpaqueType>(Ty)) {
653 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
654 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
657 switch (Ty->getTypeID()) {
658 case Type::FunctionTyID: {
659 const FunctionType *FTy = cast<FunctionType>(Ty);
660 std::stringstream FunctionInnards;
661 FunctionInnards << " (" << NameSoFar << ") (";
663 for (FunctionType::param_iterator I = FTy->param_begin(),
664 E = FTy->param_end(); I != E; ++I) {
665 const Type *ArgTy = *I;
666 if (PAL.paramHasAttr(Idx, ParamAttr::ByVal)) {
667 assert(isa<PointerType>(ArgTy));
668 ArgTy = cast<PointerType>(ArgTy)->getElementType();
670 if (I != FTy->param_begin())
671 FunctionInnards << ", ";
672 printType(FunctionInnards, ArgTy,
673 /*isSigned=*/PAL.paramHasAttr(Idx, ParamAttr::SExt), "");
676 if (FTy->isVarArg()) {
677 if (FTy->getNumParams())
678 FunctionInnards << ", ...";
679 } else if (!FTy->getNumParams()) {
680 FunctionInnards << "void";
682 FunctionInnards << ')';
683 std::string tstr = FunctionInnards.str();
684 printType(Out, FTy->getReturnType(),
685 /*isSigned=*/PAL.paramHasAttr(0, ParamAttr::SExt), tstr);
688 case Type::StructTyID: {
689 const StructType *STy = cast<StructType>(Ty);
690 Out << NameSoFar + " {\n";
692 for (StructType::element_iterator I = STy->element_begin(),
693 E = STy->element_end(); I != E; ++I) {
695 printType(Out, *I, false, "field" + utostr(Idx++));
700 Out << " __attribute__ ((packed))";
704 case Type::PointerTyID: {
705 const PointerType *PTy = cast<PointerType>(Ty);
706 std::string ptrName = "*" + NameSoFar;
708 if (isa<ArrayType>(PTy->getElementType()) ||
709 isa<VectorType>(PTy->getElementType()))
710 ptrName = "(" + ptrName + ")";
713 // Must be a function ptr cast!
714 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
715 return printType(Out, PTy->getElementType(), false, ptrName);
718 case Type::ArrayTyID: {
719 const ArrayType *ATy = cast<ArrayType>(Ty);
720 unsigned NumElements = ATy->getNumElements();
721 if (NumElements == 0) NumElements = 1;
722 // Arrays are wrapped in structs to allow them to have normal
723 // value semantics (avoiding the array "decay").
724 Out << NameSoFar << " { ";
725 printType(Out, ATy->getElementType(), false,
726 "array[" + utostr(NumElements) + "]");
730 case Type::OpaqueTyID: {
731 static int Count = 0;
732 std::string TyName = "struct opaque_" + itostr(Count++);
733 assert(TypeNames.find(Ty) == TypeNames.end());
734 TypeNames[Ty] = TyName;
735 return Out << TyName << ' ' << NameSoFar;
738 assert(0 && "Unhandled case in getTypeProps!");
745 void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
747 // As a special case, print the array as a string if it is an array of
748 // ubytes or an array of sbytes with positive values.
750 const Type *ETy = CPA->getType()->getElementType();
751 bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty);
753 // Make sure the last character is a null char, as automatically added by C
754 if (isString && (CPA->getNumOperands() == 0 ||
755 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
760 // Keep track of whether the last number was a hexadecimal escape
761 bool LastWasHex = false;
763 // Do not include the last character, which we know is null
764 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
765 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
767 // Print it out literally if it is a printable character. The only thing
768 // to be careful about is when the last letter output was a hex escape
769 // code, in which case we have to be careful not to print out hex digits
770 // explicitly (the C compiler thinks it is a continuation of the previous
771 // character, sheesh...)
773 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
775 if (C == '"' || C == '\\')
776 Out << "\\" << (char)C;
782 case '\n': Out << "\\n"; break;
783 case '\t': Out << "\\t"; break;
784 case '\r': Out << "\\r"; break;
785 case '\v': Out << "\\v"; break;
786 case '\a': Out << "\\a"; break;
787 case '\"': Out << "\\\""; break;
788 case '\'': Out << "\\\'"; break;
791 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
792 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
801 if (CPA->getNumOperands()) {
803 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
804 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
806 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
813 void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
815 if (CP->getNumOperands()) {
817 printConstant(cast<Constant>(CP->getOperand(0)), Static);
818 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
820 printConstant(cast<Constant>(CP->getOperand(i)), Static);
826 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
827 // textually as a double (rather than as a reference to a stack-allocated
828 // variable). We decide this by converting CFP to a string and back into a
829 // double, and then checking whether the conversion results in a bit-equal
830 // double to the original value of CFP. This depends on us and the target C
831 // compiler agreeing on the conversion process (which is pretty likely since we
832 // only deal in IEEE FP).
834 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
835 // Do long doubles in hex for now.
836 if (CFP->getType()!=Type::FloatTy && CFP->getType()!=Type::DoubleTy)
838 APFloat APF = APFloat(CFP->getValueAPF()); // copy
839 if (CFP->getType()==Type::FloatTy)
840 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
841 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
843 sprintf(Buffer, "%a", APF.convertToDouble());
844 if (!strncmp(Buffer, "0x", 2) ||
845 !strncmp(Buffer, "-0x", 3) ||
846 !strncmp(Buffer, "+0x", 3))
847 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
850 std::string StrVal = ftostr(APF);
852 while (StrVal[0] == ' ')
853 StrVal.erase(StrVal.begin());
855 // Check to make sure that the stringized number is not some string like "Inf"
856 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
857 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
858 ((StrVal[0] == '-' || StrVal[0] == '+') &&
859 (StrVal[1] >= '0' && StrVal[1] <= '9')))
860 // Reparse stringized version!
861 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
866 /// Print out the casting for a cast operation. This does the double casting
867 /// necessary for conversion to the destination type, if necessary.
868 /// @brief Print a cast
869 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
870 // Print the destination type cast
872 case Instruction::UIToFP:
873 case Instruction::SIToFP:
874 case Instruction::IntToPtr:
875 case Instruction::Trunc:
876 case Instruction::BitCast:
877 case Instruction::FPExt:
878 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
880 printType(Out, DstTy);
883 case Instruction::ZExt:
884 case Instruction::PtrToInt:
885 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
887 printSimpleType(Out, DstTy, false);
890 case Instruction::SExt:
891 case Instruction::FPToSI: // For these, make sure we get a signed dest
893 printSimpleType(Out, DstTy, true);
897 assert(0 && "Invalid cast opcode");
900 // Print the source type cast
902 case Instruction::UIToFP:
903 case Instruction::ZExt:
905 printSimpleType(Out, SrcTy, false);
908 case Instruction::SIToFP:
909 case Instruction::SExt:
911 printSimpleType(Out, SrcTy, true);
914 case Instruction::IntToPtr:
915 case Instruction::PtrToInt:
916 // Avoid "cast to pointer from integer of different size" warnings
917 Out << "(unsigned long)";
919 case Instruction::Trunc:
920 case Instruction::BitCast:
921 case Instruction::FPExt:
922 case Instruction::FPTrunc:
923 case Instruction::FPToSI:
924 case Instruction::FPToUI:
925 break; // These don't need a source cast.
927 assert(0 && "Invalid cast opcode");
932 // printConstant - The LLVM Constant to C Constant converter.
933 void CWriter::printConstant(Constant *CPV, bool Static) {
934 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
935 switch (CE->getOpcode()) {
936 case Instruction::Trunc:
937 case Instruction::ZExt:
938 case Instruction::SExt:
939 case Instruction::FPTrunc:
940 case Instruction::FPExt:
941 case Instruction::UIToFP:
942 case Instruction::SIToFP:
943 case Instruction::FPToUI:
944 case Instruction::FPToSI:
945 case Instruction::PtrToInt:
946 case Instruction::IntToPtr:
947 case Instruction::BitCast:
949 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
950 if (CE->getOpcode() == Instruction::SExt &&
951 CE->getOperand(0)->getType() == Type::Int1Ty) {
952 // Make sure we really sext from bool here by subtracting from 0
955 printConstant(CE->getOperand(0), Static);
956 if (CE->getType() == Type::Int1Ty &&
957 (CE->getOpcode() == Instruction::Trunc ||
958 CE->getOpcode() == Instruction::FPToUI ||
959 CE->getOpcode() == Instruction::FPToSI ||
960 CE->getOpcode() == Instruction::PtrToInt)) {
961 // Make sure we really truncate to bool here by anding with 1
967 case Instruction::GetElementPtr:
969 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
970 gep_type_end(CPV), Static);
973 case Instruction::Select:
975 printConstant(CE->getOperand(0), Static);
977 printConstant(CE->getOperand(1), Static);
979 printConstant(CE->getOperand(2), Static);
982 case Instruction::Add:
983 case Instruction::Sub:
984 case Instruction::Mul:
985 case Instruction::SDiv:
986 case Instruction::UDiv:
987 case Instruction::FDiv:
988 case Instruction::URem:
989 case Instruction::SRem:
990 case Instruction::FRem:
991 case Instruction::And:
992 case Instruction::Or:
993 case Instruction::Xor:
994 case Instruction::ICmp:
995 case Instruction::Shl:
996 case Instruction::LShr:
997 case Instruction::AShr:
1000 bool NeedsClosingParens = printConstExprCast(CE, Static);
1001 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1002 switch (CE->getOpcode()) {
1003 case Instruction::Add: Out << " + "; break;
1004 case Instruction::Sub: Out << " - "; break;
1005 case Instruction::Mul: Out << " * "; break;
1006 case Instruction::URem:
1007 case Instruction::SRem:
1008 case Instruction::FRem: Out << " % "; break;
1009 case Instruction::UDiv:
1010 case Instruction::SDiv:
1011 case Instruction::FDiv: Out << " / "; break;
1012 case Instruction::And: Out << " & "; break;
1013 case Instruction::Or: Out << " | "; break;
1014 case Instruction::Xor: Out << " ^ "; break;
1015 case Instruction::Shl: Out << " << "; break;
1016 case Instruction::LShr:
1017 case Instruction::AShr: Out << " >> "; break;
1018 case Instruction::ICmp:
1019 switch (CE->getPredicate()) {
1020 case ICmpInst::ICMP_EQ: Out << " == "; break;
1021 case ICmpInst::ICMP_NE: Out << " != "; break;
1022 case ICmpInst::ICMP_SLT:
1023 case ICmpInst::ICMP_ULT: Out << " < "; break;
1024 case ICmpInst::ICMP_SLE:
1025 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1026 case ICmpInst::ICMP_SGT:
1027 case ICmpInst::ICMP_UGT: Out << " > "; break;
1028 case ICmpInst::ICMP_SGE:
1029 case ICmpInst::ICMP_UGE: Out << " >= "; break;
1030 default: assert(0 && "Illegal ICmp predicate");
1033 default: assert(0 && "Illegal opcode here!");
1035 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1036 if (NeedsClosingParens)
1041 case Instruction::FCmp: {
1043 bool NeedsClosingParens = printConstExprCast(CE, Static);
1044 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1046 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1050 switch (CE->getPredicate()) {
1051 default: assert(0 && "Illegal FCmp predicate");
1052 case FCmpInst::FCMP_ORD: op = "ord"; break;
1053 case FCmpInst::FCMP_UNO: op = "uno"; break;
1054 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1055 case FCmpInst::FCMP_UNE: op = "une"; break;
1056 case FCmpInst::FCMP_ULT: op = "ult"; break;
1057 case FCmpInst::FCMP_ULE: op = "ule"; break;
1058 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1059 case FCmpInst::FCMP_UGE: op = "uge"; break;
1060 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1061 case FCmpInst::FCMP_ONE: op = "one"; break;
1062 case FCmpInst::FCMP_OLT: op = "olt"; break;
1063 case FCmpInst::FCMP_OLE: op = "ole"; break;
1064 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1065 case FCmpInst::FCMP_OGE: op = "oge"; break;
1067 Out << "llvm_fcmp_" << op << "(";
1068 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1070 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1073 if (NeedsClosingParens)
1079 cerr << "CWriter Error: Unhandled constant expression: "
1083 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
1085 printType(Out, CPV->getType()); // sign doesn't matter
1086 Out << ")/*UNDEF*/";
1087 if (!isa<VectorType>(CPV->getType())) {
1095 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1096 const Type* Ty = CI->getType();
1097 if (Ty == Type::Int1Ty)
1098 Out << (CI->getZExtValue() ? '1' : '0');
1099 else if (Ty == Type::Int32Ty)
1100 Out << CI->getZExtValue() << 'u';
1101 else if (Ty->getPrimitiveSizeInBits() > 32)
1102 Out << CI->getZExtValue() << "ull";
1105 printSimpleType(Out, Ty, false) << ')';
1106 if (CI->isMinValue(true))
1107 Out << CI->getZExtValue() << 'u';
1109 Out << CI->getSExtValue();
1115 switch (CPV->getType()->getTypeID()) {
1116 case Type::FloatTyID:
1117 case Type::DoubleTyID:
1118 case Type::X86_FP80TyID:
1119 case Type::PPC_FP128TyID:
1120 case Type::FP128TyID: {
1121 ConstantFP *FPC = cast<ConstantFP>(CPV);
1122 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
1123 if (I != FPConstantMap.end()) {
1124 // Because of FP precision problems we must load from a stack allocated
1125 // value that holds the value in hex.
1126 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" :
1127 FPC->getType() == Type::DoubleTy ? "double" :
1129 << "*)&FPConstant" << I->second << ')';
1131 assert(FPC->getType() == Type::FloatTy ||
1132 FPC->getType() == Type::DoubleTy);
1133 double V = FPC->getType() == Type::FloatTy ?
1134 FPC->getValueAPF().convertToFloat() :
1135 FPC->getValueAPF().convertToDouble();
1139 // FIXME the actual NaN bits should be emitted.
1140 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1142 const unsigned long QuietNaN = 0x7ff8UL;
1143 //const unsigned long SignalNaN = 0x7ff4UL;
1145 // We need to grab the first part of the FP #
1148 uint64_t ll = DoubleToBits(V);
1149 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
1151 std::string Num(&Buffer[0], &Buffer[6]);
1152 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1154 if (FPC->getType() == Type::FloatTy)
1155 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1156 << Buffer << "\") /*nan*/ ";
1158 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1159 << Buffer << "\") /*nan*/ ";
1160 } else if (IsInf(V)) {
1162 if (V < 0) Out << '-';
1163 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
1167 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1168 // Print out the constant as a floating point number.
1170 sprintf(Buffer, "%a", V);
1173 Num = ftostr(FPC->getValueAPF());
1181 case Type::ArrayTyID:
1182 // Use C99 compound expression literal initializer syntax.
1185 printType(Out, CPV->getType());
1188 Out << "{ "; // Arrays are wrapped in struct types.
1189 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
1190 printConstantArray(CA, Static);
1192 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1193 const ArrayType *AT = cast<ArrayType>(CPV->getType());
1195 if (AT->getNumElements()) {
1197 Constant *CZ = Constant::getNullValue(AT->getElementType());
1198 printConstant(CZ, Static);
1199 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1201 printConstant(CZ, Static);
1206 Out << " }"; // Arrays are wrapped in struct types.
1209 case Type::VectorTyID:
1210 // Use C99 compound expression literal initializer syntax.
1213 printType(Out, CPV->getType());
1216 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
1217 printConstantVector(CV, Static);
1219 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1220 const VectorType *VT = cast<VectorType>(CPV->getType());
1222 Constant *CZ = Constant::getNullValue(VT->getElementType());
1223 printConstant(CZ, Static);
1224 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
1226 printConstant(CZ, Static);
1232 case Type::StructTyID:
1233 // Use C99 compound expression literal initializer syntax.
1236 printType(Out, CPV->getType());
1239 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1240 const StructType *ST = cast<StructType>(CPV->getType());
1242 if (ST->getNumElements()) {
1244 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
1245 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1247 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
1253 if (CPV->getNumOperands()) {
1255 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
1256 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1258 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
1265 case Type::PointerTyID:
1266 if (isa<ConstantPointerNull>(CPV)) {
1268 printType(Out, CPV->getType()); // sign doesn't matter
1269 Out << ")/*NULL*/0)";
1271 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1272 writeOperand(GV, Static);
1277 cerr << "Unknown constant type: " << *CPV << "\n";
1282 // Some constant expressions need to be casted back to the original types
1283 // because their operands were casted to the expected type. This function takes
1284 // care of detecting that case and printing the cast for the ConstantExpr.
1285 bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
1286 bool NeedsExplicitCast = false;
1287 const Type *Ty = CE->getOperand(0)->getType();
1288 bool TypeIsSigned = false;
1289 switch (CE->getOpcode()) {
1290 case Instruction::Add:
1291 case Instruction::Sub:
1292 case Instruction::Mul:
1293 // We need to cast integer arithmetic so that it is always performed
1294 // as unsigned, to avoid undefined behavior on overflow.
1295 if (!Ty->isIntOrIntVector()) break;
1297 case Instruction::LShr:
1298 case Instruction::URem:
1299 case Instruction::UDiv: NeedsExplicitCast = true; break;
1300 case Instruction::AShr:
1301 case Instruction::SRem:
1302 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1303 case Instruction::SExt:
1305 NeedsExplicitCast = true;
1306 TypeIsSigned = true;
1308 case Instruction::ZExt:
1309 case Instruction::Trunc:
1310 case Instruction::FPTrunc:
1311 case Instruction::FPExt:
1312 case Instruction::UIToFP:
1313 case Instruction::SIToFP:
1314 case Instruction::FPToUI:
1315 case Instruction::FPToSI:
1316 case Instruction::PtrToInt:
1317 case Instruction::IntToPtr:
1318 case Instruction::BitCast:
1320 NeedsExplicitCast = true;
1324 if (NeedsExplicitCast) {
1326 if (Ty->isInteger() && Ty != Type::Int1Ty)
1327 printSimpleType(Out, Ty, TypeIsSigned);
1329 printType(Out, Ty); // not integer, sign doesn't matter
1332 return NeedsExplicitCast;
1335 // Print a constant assuming that it is the operand for a given Opcode. The
1336 // opcodes that care about sign need to cast their operands to the expected
1337 // type before the operation proceeds. This function does the casting.
1338 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1340 // Extract the operand's type, we'll need it.
1341 const Type* OpTy = CPV->getType();
1343 // Indicate whether to do the cast or not.
1344 bool shouldCast = false;
1345 bool typeIsSigned = false;
1347 // Based on the Opcode for which this Constant is being written, determine
1348 // the new type to which the operand should be casted by setting the value
1349 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1353 // for most instructions, it doesn't matter
1355 case Instruction::Add:
1356 case Instruction::Sub:
1357 case Instruction::Mul:
1358 // We need to cast integer arithmetic so that it is always performed
1359 // as unsigned, to avoid undefined behavior on overflow.
1360 if (!OpTy->isIntOrIntVector()) break;
1362 case Instruction::LShr:
1363 case Instruction::UDiv:
1364 case Instruction::URem:
1367 case Instruction::AShr:
1368 case Instruction::SDiv:
1369 case Instruction::SRem:
1371 typeIsSigned = true;
1375 // Write out the casted constant if we should, otherwise just write the
1379 printSimpleType(Out, OpTy, typeIsSigned);
1381 printConstant(CPV, false);
1384 printConstant(CPV, false);
1387 std::string CWriter::GetValueName(const Value *Operand) {
1390 if (!isa<GlobalValue>(Operand) && Operand->getName() != "") {
1391 std::string VarName;
1393 Name = Operand->getName();
1394 VarName.reserve(Name.capacity());
1396 for (std::string::iterator I = Name.begin(), E = Name.end();
1400 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1401 (ch >= '0' && ch <= '9') || ch == '_')) {
1403 sprintf(buffer, "_%x_", ch);
1409 Name = "llvm_cbe_" + VarName;
1411 Name = Mang->getValueName(Operand);
1417 /// writeInstComputationInline - Emit the computation for the specified
1418 /// instruction inline, with no destination provided.
1419 void CWriter::writeInstComputationInline(Instruction &I) {
1420 // If this is a non-trivial bool computation, make sure to truncate down to
1421 // a 1 bit value. This is important because we want "add i1 x, y" to return
1422 // "0" when x and y are true, not "2" for example.
1423 bool NeedBoolTrunc = false;
1424 if (I.getType() == Type::Int1Ty && !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
1425 NeedBoolTrunc = true;
1437 void CWriter::writeOperandInternal(Value *Operand, bool Static) {
1438 if (Instruction *I = dyn_cast<Instruction>(Operand))
1439 // Should we inline this instruction to build a tree?
1440 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1442 writeInstComputationInline(*I);
1447 Constant* CPV = dyn_cast<Constant>(Operand);
1449 if (CPV && !isa<GlobalValue>(CPV))
1450 printConstant(CPV, Static);
1452 Out << GetValueName(Operand);
1455 void CWriter::writeOperand(Value *Operand, bool Static) {
1456 bool isAddressImplicit = isAddressExposed(Operand);
1457 if (isAddressImplicit)
1458 Out << "(&"; // Global variables are referenced as their addresses by llvm
1460 writeOperandInternal(Operand, Static);
1462 if (isAddressImplicit)
1466 // Some instructions need to have their result value casted back to the
1467 // original types because their operands were casted to the expected type.
1468 // This function takes care of detecting that case and printing the cast
1469 // for the Instruction.
1470 bool CWriter::writeInstructionCast(const Instruction &I) {
1471 const Type *Ty = I.getOperand(0)->getType();
1472 switch (I.getOpcode()) {
1473 case Instruction::Add:
1474 case Instruction::Sub:
1475 case Instruction::Mul:
1476 // We need to cast integer arithmetic so that it is always performed
1477 // as unsigned, to avoid undefined behavior on overflow.
1478 if (!Ty->isIntOrIntVector()) break;
1480 case Instruction::LShr:
1481 case Instruction::URem:
1482 case Instruction::UDiv:
1484 printSimpleType(Out, Ty, false);
1487 case Instruction::AShr:
1488 case Instruction::SRem:
1489 case Instruction::SDiv:
1491 printSimpleType(Out, Ty, true);
1499 // Write the operand with a cast to another type based on the Opcode being used.
1500 // This will be used in cases where an instruction has specific type
1501 // requirements (usually signedness) for its operands.
1502 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1504 // Extract the operand's type, we'll need it.
1505 const Type* OpTy = Operand->getType();
1507 // Indicate whether to do the cast or not.
1508 bool shouldCast = false;
1510 // Indicate whether the cast should be to a signed type or not.
1511 bool castIsSigned = false;
1513 // Based on the Opcode for which this Operand is being written, determine
1514 // the new type to which the operand should be casted by setting the value
1515 // of OpTy. If we change OpTy, also set shouldCast to true.
1518 // for most instructions, it doesn't matter
1520 case Instruction::Add:
1521 case Instruction::Sub:
1522 case Instruction::Mul:
1523 // We need to cast integer arithmetic so that it is always performed
1524 // as unsigned, to avoid undefined behavior on overflow.
1525 if (!OpTy->isIntOrIntVector()) break;
1527 case Instruction::LShr:
1528 case Instruction::UDiv:
1529 case Instruction::URem: // Cast to unsigned first
1531 castIsSigned = false;
1533 case Instruction::GetElementPtr:
1534 case Instruction::AShr:
1535 case Instruction::SDiv:
1536 case Instruction::SRem: // Cast to signed first
1538 castIsSigned = true;
1542 // Write out the casted operand if we should, otherwise just write the
1546 printSimpleType(Out, OpTy, castIsSigned);
1548 writeOperand(Operand);
1551 writeOperand(Operand);
1554 // Write the operand with a cast to another type based on the icmp predicate
1556 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1557 // This has to do a cast to ensure the operand has the right signedness.
1558 // Also, if the operand is a pointer, we make sure to cast to an integer when
1559 // doing the comparison both for signedness and so that the C compiler doesn't
1560 // optimize things like "p < NULL" to false (p may contain an integer value
1562 bool shouldCast = Cmp.isRelational();
1564 // Write out the casted operand if we should, otherwise just write the
1567 writeOperand(Operand);
1571 // Should this be a signed comparison? If so, convert to signed.
1572 bool castIsSigned = Cmp.isSignedPredicate();
1574 // If the operand was a pointer, convert to a large integer type.
1575 const Type* OpTy = Operand->getType();
1576 if (isa<PointerType>(OpTy))
1577 OpTy = TD->getIntPtrType();
1580 printSimpleType(Out, OpTy, castIsSigned);
1582 writeOperand(Operand);
1586 // generateCompilerSpecificCode - This is where we add conditional compilation
1587 // directives to cater to specific compilers as need be.
1589 static void generateCompilerSpecificCode(raw_ostream& Out,
1590 const TargetData *TD) {
1591 // Alloca is hard to get, and we don't want to include stdlib.h here.
1592 Out << "/* get a declaration for alloca */\n"
1593 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1594 << "#define alloca(x) __builtin_alloca((x))\n"
1595 << "#define _alloca(x) __builtin_alloca((x))\n"
1596 << "#elif defined(__APPLE__)\n"
1597 << "extern void *__builtin_alloca(unsigned long);\n"
1598 << "#define alloca(x) __builtin_alloca(x)\n"
1599 << "#define longjmp _longjmp\n"
1600 << "#define setjmp _setjmp\n"
1601 << "#elif defined(__sun__)\n"
1602 << "#if defined(__sparcv9)\n"
1603 << "extern void *__builtin_alloca(unsigned long);\n"
1605 << "extern void *__builtin_alloca(unsigned int);\n"
1607 << "#define alloca(x) __builtin_alloca(x)\n"
1608 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)\n"
1609 << "#define alloca(x) __builtin_alloca(x)\n"
1610 << "#elif defined(_MSC_VER)\n"
1611 << "#define inline _inline\n"
1612 << "#define alloca(x) _alloca(x)\n"
1614 << "#include <alloca.h>\n"
1617 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1618 // If we aren't being compiled with GCC, just drop these attributes.
1619 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1620 << "#define __attribute__(X)\n"
1623 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1624 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1625 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1626 << "#elif defined(__GNUC__)\n"
1627 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1629 << "#define __EXTERNAL_WEAK__\n"
1632 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1633 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1634 << "#define __ATTRIBUTE_WEAK__\n"
1635 << "#elif defined(__GNUC__)\n"
1636 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1638 << "#define __ATTRIBUTE_WEAK__\n"
1641 // Add hidden visibility support. FIXME: APPLE_CC?
1642 Out << "#if defined(__GNUC__)\n"
1643 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1646 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1647 // From the GCC documentation:
1649 // double __builtin_nan (const char *str)
1651 // This is an implementation of the ISO C99 function nan.
1653 // Since ISO C99 defines this function in terms of strtod, which we do
1654 // not implement, a description of the parsing is in order. The string is
1655 // parsed as by strtol; that is, the base is recognized by leading 0 or
1656 // 0x prefixes. The number parsed is placed in the significand such that
1657 // the least significant bit of the number is at the least significant
1658 // bit of the significand. The number is truncated to fit the significand
1659 // field provided. The significand is forced to be a quiet NaN.
1661 // This function, if given a string literal, is evaluated early enough
1662 // that it is considered a compile-time constant.
1664 // float __builtin_nanf (const char *str)
1666 // Similar to __builtin_nan, except the return type is float.
1668 // double __builtin_inf (void)
1670 // Similar to __builtin_huge_val, except a warning is generated if the
1671 // target floating-point format does not support infinities. This
1672 // function is suitable for implementing the ISO C99 macro INFINITY.
1674 // float __builtin_inff (void)
1676 // Similar to __builtin_inf, except the return type is float.
1677 Out << "#ifdef __GNUC__\n"
1678 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1679 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1680 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1681 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1682 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1683 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1684 << "#define LLVM_PREFETCH(addr,rw,locality) "
1685 "__builtin_prefetch(addr,rw,locality)\n"
1686 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1687 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1688 << "#define LLVM_ASM __asm__\n"
1690 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1691 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1692 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1693 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1694 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1695 << "#define LLVM_INFF 0.0F /* Float */\n"
1696 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1697 << "#define __ATTRIBUTE_CTOR__\n"
1698 << "#define __ATTRIBUTE_DTOR__\n"
1699 << "#define LLVM_ASM(X)\n"
1702 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1703 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1704 << "#define __builtin_stack_restore(X) /* noop */\n"
1707 // Output typedefs for 128-bit integers. If these are needed with a
1708 // 32-bit target or with a C compiler that doesn't support mode(TI),
1709 // more drastic measures will be needed.
1710 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1711 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1712 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1715 // Output target-specific code that should be inserted into main.
1716 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1719 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1720 /// the StaticTors set.
1721 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1722 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1723 if (!InitList) return;
1725 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1726 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1727 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1729 if (CS->getOperand(1)->isNullValue())
1730 return; // Found a null terminator, exit printing.
1731 Constant *FP = CS->getOperand(1);
1732 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1734 FP = CE->getOperand(0);
1735 if (Function *F = dyn_cast<Function>(FP))
1736 StaticTors.insert(F);
1740 enum SpecialGlobalClass {
1742 GlobalCtors, GlobalDtors,
1746 /// getGlobalVariableClass - If this is a global that is specially recognized
1747 /// by LLVM, return a code that indicates how we should handle it.
1748 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1749 // If this is a global ctors/dtors list, handle it now.
1750 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1751 if (GV->getName() == "llvm.global_ctors")
1753 else if (GV->getName() == "llvm.global_dtors")
1757 // Otherwise, it it is other metadata, don't print it. This catches things
1758 // like debug information.
1759 if (GV->getSection() == "llvm.metadata")
1766 bool CWriter::doInitialization(Module &M) {
1770 TD = new TargetData(&M);
1771 IL = new IntrinsicLowering(*TD);
1772 IL->AddPrototypes(M);
1774 // Ensure that all structure types have names...
1775 Mang = new Mangler(M);
1776 Mang->markCharUnacceptable('.');
1778 // Keep track of which functions are static ctors/dtors so they can have
1779 // an attribute added to their prototypes.
1780 std::set<Function*> StaticCtors, StaticDtors;
1781 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1783 switch (getGlobalVariableClass(I)) {
1786 FindStaticTors(I, StaticCtors);
1789 FindStaticTors(I, StaticDtors);
1794 // get declaration for alloca
1795 Out << "/* Provide Declarations */\n";
1796 Out << "#include <stdarg.h>\n"; // Varargs support
1797 Out << "#include <setjmp.h>\n"; // Unwind support
1798 generateCompilerSpecificCode(Out, TD);
1800 // Provide a definition for `bool' if not compiling with a C++ compiler.
1802 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1804 << "\n\n/* Support for floating point constants */\n"
1805 << "typedef unsigned long long ConstantDoubleTy;\n"
1806 << "typedef unsigned int ConstantFloatTy;\n"
1807 << "typedef struct { unsigned long long f1; unsigned short f2; "
1808 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1809 // This is used for both kinds of 128-bit long double; meaning differs.
1810 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1811 " ConstantFP128Ty;\n"
1812 << "\n\n/* Global Declarations */\n";
1814 // First output all the declarations for the program, because C requires
1815 // Functions & globals to be declared before they are used.
1818 // Loop over the symbol table, emitting all named constants...
1819 printModuleTypes(M.getTypeSymbolTable());
1821 // Global variable declarations...
1822 if (!M.global_empty()) {
1823 Out << "\n/* External Global Variable Declarations */\n";
1824 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1827 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1828 I->hasCommonLinkage())
1830 else if (I->hasDLLImportLinkage())
1831 Out << "__declspec(dllimport) ";
1833 continue; // Internal Global
1835 // Thread Local Storage
1836 if (I->isThreadLocal())
1839 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1841 if (I->hasExternalWeakLinkage())
1842 Out << " __EXTERNAL_WEAK__";
1847 // Function declarations
1848 Out << "\n/* Function Declarations */\n";
1849 Out << "double fmod(double, double);\n"; // Support for FP rem
1850 Out << "float fmodf(float, float);\n";
1851 Out << "long double fmodl(long double, long double);\n";
1853 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1854 // Don't print declarations for intrinsic functions.
1855 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
1856 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1857 if (I->hasExternalWeakLinkage())
1859 printFunctionSignature(I, true);
1860 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1861 Out << " __ATTRIBUTE_WEAK__";
1862 if (I->hasExternalWeakLinkage())
1863 Out << " __EXTERNAL_WEAK__";
1864 if (StaticCtors.count(I))
1865 Out << " __ATTRIBUTE_CTOR__";
1866 if (StaticDtors.count(I))
1867 Out << " __ATTRIBUTE_DTOR__";
1868 if (I->hasHiddenVisibility())
1869 Out << " __HIDDEN__";
1871 if (I->hasName() && I->getName()[0] == 1)
1872 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1878 // Output the global variable declarations
1879 if (!M.global_empty()) {
1880 Out << "\n\n/* Global Variable Declarations */\n";
1881 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1883 if (!I->isDeclaration()) {
1884 // Ignore special globals, such as debug info.
1885 if (getGlobalVariableClass(I))
1888 if (I->hasInternalLinkage())
1893 // Thread Local Storage
1894 if (I->isThreadLocal())
1897 printType(Out, I->getType()->getElementType(), false,
1900 if (I->hasLinkOnceLinkage())
1901 Out << " __attribute__((common))";
1902 else if (I->hasCommonLinkage()) // FIXME is this right?
1903 Out << " __ATTRIBUTE_WEAK__";
1904 else if (I->hasWeakLinkage())
1905 Out << " __ATTRIBUTE_WEAK__";
1906 else if (I->hasExternalWeakLinkage())
1907 Out << " __EXTERNAL_WEAK__";
1908 if (I->hasHiddenVisibility())
1909 Out << " __HIDDEN__";
1914 // Output the global variable definitions and contents...
1915 if (!M.global_empty()) {
1916 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1917 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1919 if (!I->isDeclaration()) {
1920 // Ignore special globals, such as debug info.
1921 if (getGlobalVariableClass(I))
1924 if (I->hasInternalLinkage())
1926 else if (I->hasDLLImportLinkage())
1927 Out << "__declspec(dllimport) ";
1928 else if (I->hasDLLExportLinkage())
1929 Out << "__declspec(dllexport) ";
1931 // Thread Local Storage
1932 if (I->isThreadLocal())
1935 printType(Out, I->getType()->getElementType(), false,
1937 if (I->hasLinkOnceLinkage())
1938 Out << " __attribute__((common))";
1939 else if (I->hasWeakLinkage())
1940 Out << " __ATTRIBUTE_WEAK__";
1941 else if (I->hasCommonLinkage())
1942 Out << " __ATTRIBUTE_WEAK__";
1944 if (I->hasHiddenVisibility())
1945 Out << " __HIDDEN__";
1947 // If the initializer is not null, emit the initializer. If it is null,
1948 // we try to avoid emitting large amounts of zeros. The problem with
1949 // this, however, occurs when the variable has weak linkage. In this
1950 // case, the assembler will complain about the variable being both weak
1951 // and common, so we disable this optimization.
1952 // FIXME common linkage should avoid this problem.
1953 if (!I->getInitializer()->isNullValue()) {
1955 writeOperand(I->getInitializer(), true);
1956 } else if (I->hasWeakLinkage()) {
1957 // We have to specify an initializer, but it doesn't have to be
1958 // complete. If the value is an aggregate, print out { 0 }, and let
1959 // the compiler figure out the rest of the zeros.
1961 if (isa<StructType>(I->getInitializer()->getType()) ||
1962 isa<VectorType>(I->getInitializer()->getType())) {
1964 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
1965 // As with structs and vectors, but with an extra set of braces
1966 // because arrays are wrapped in structs.
1969 // Just print it out normally.
1970 writeOperand(I->getInitializer(), true);
1978 Out << "\n\n/* Function Bodies */\n";
1980 // Emit some helper functions for dealing with FCMP instruction's
1982 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
1983 Out << "return X == X && Y == Y; }\n";
1984 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
1985 Out << "return X != X || Y != Y; }\n";
1986 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
1987 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
1988 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
1989 Out << "return X != Y; }\n";
1990 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
1991 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
1992 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
1993 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
1994 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
1995 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
1996 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
1997 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
1998 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
1999 Out << "return X == Y ; }\n";
2000 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
2001 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
2002 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
2003 Out << "return X < Y ; }\n";
2004 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
2005 Out << "return X > Y ; }\n";
2006 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
2007 Out << "return X <= Y ; }\n";
2008 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
2009 Out << "return X >= Y ; }\n";
2014 /// Output all floating point constants that cannot be printed accurately...
2015 void CWriter::printFloatingPointConstants(Function &F) {
2016 // Scan the module for floating point constants. If any FP constant is used
2017 // in the function, we want to redirect it here so that we do not depend on
2018 // the precision of the printed form, unless the printed form preserves
2021 static unsigned FPCounter = 0;
2022 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2024 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
2025 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
2026 !FPConstantMap.count(FPC)) {
2027 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2029 if (FPC->getType() == Type::DoubleTy) {
2030 double Val = FPC->getValueAPF().convertToDouble();
2031 uint64_t i = FPC->getValueAPF().convertToAPInt().getZExtValue();
2032 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2033 << " = 0x" << utohexstr(i)
2034 << "ULL; /* " << Val << " */\n";
2035 } else if (FPC->getType() == Type::FloatTy) {
2036 float Val = FPC->getValueAPF().convertToFloat();
2037 uint32_t i = (uint32_t)FPC->getValueAPF().convertToAPInt().
2039 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2040 << " = 0x" << utohexstr(i)
2041 << "U; /* " << Val << " */\n";
2042 } else if (FPC->getType() == Type::X86_FP80Ty) {
2043 // api needed to prevent premature destruction
2044 APInt api = FPC->getValueAPF().convertToAPInt();
2045 const uint64_t *p = api.getRawData();
2046 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
2048 << utohexstr((uint16_t)p[1] | (p[0] & 0xffffffffffffLL)<<16)
2049 << "ULL, 0x" << utohexstr((uint16_t)(p[0] >> 48)) << ",{0,0,0}"
2050 << "}; /* Long double constant */\n";
2051 } else if (FPC->getType() == Type::PPC_FP128Ty) {
2052 APInt api = FPC->getValueAPF().convertToAPInt();
2053 const uint64_t *p = api.getRawData();
2054 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2056 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2057 << "}; /* Long double constant */\n";
2060 assert(0 && "Unknown float type!");
2067 /// printSymbolTable - Run through symbol table looking for type names. If a
2068 /// type name is found, emit its declaration...
2070 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
2071 Out << "/* Helper union for bitcasts */\n";
2072 Out << "typedef union {\n";
2073 Out << " unsigned int Int32;\n";
2074 Out << " unsigned long long Int64;\n";
2075 Out << " float Float;\n";
2076 Out << " double Double;\n";
2077 Out << "} llvmBitCastUnion;\n";
2079 // We are only interested in the type plane of the symbol table.
2080 TypeSymbolTable::const_iterator I = TST.begin();
2081 TypeSymbolTable::const_iterator End = TST.end();
2083 // If there are no type names, exit early.
2084 if (I == End) return;
2086 // Print out forward declarations for structure types before anything else!
2087 Out << "/* Structure forward decls */\n";
2088 for (; I != End; ++I) {
2089 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
2090 Out << Name << ";\n";
2091 TypeNames.insert(std::make_pair(I->second, Name));
2096 // Now we can print out typedefs. Above, we guaranteed that this can only be
2097 // for struct or opaque types.
2098 Out << "/* Typedefs */\n";
2099 for (I = TST.begin(); I != End; ++I) {
2100 std::string Name = "l_" + Mang->makeNameProper(I->first);
2102 printType(Out, I->second, false, Name);
2108 // Keep track of which structures have been printed so far...
2109 std::set<const Type *> StructPrinted;
2111 // Loop over all structures then push them into the stack so they are
2112 // printed in the correct order.
2114 Out << "/* Structure contents */\n";
2115 for (I = TST.begin(); I != End; ++I)
2116 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
2117 // Only print out used types!
2118 printContainedStructs(I->second, StructPrinted);
2121 // Push the struct onto the stack and recursively push all structs
2122 // this one depends on.
2124 // TODO: Make this work properly with vector types
2126 void CWriter::printContainedStructs(const Type *Ty,
2127 std::set<const Type*> &StructPrinted) {
2128 // Don't walk through pointers.
2129 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
2131 // Print all contained types first.
2132 for (Type::subtype_iterator I = Ty->subtype_begin(),
2133 E = Ty->subtype_end(); I != E; ++I)
2134 printContainedStructs(*I, StructPrinted);
2136 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
2137 // Check to see if we have already printed this struct.
2138 if (StructPrinted.insert(Ty).second) {
2139 // Print structure type out.
2140 std::string Name = TypeNames[Ty];
2141 printType(Out, Ty, false, Name, true);
2147 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
2148 /// isStructReturn - Should this function actually return a struct by-value?
2149 bool isStructReturn = F->hasStructRetAttr();
2151 if (F->hasInternalLinkage()) Out << "static ";
2152 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2153 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
2154 switch (F->getCallingConv()) {
2155 case CallingConv::X86_StdCall:
2156 Out << "__stdcall ";
2158 case CallingConv::X86_FastCall:
2159 Out << "__fastcall ";
2163 // Loop over the arguments, printing them...
2164 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
2165 const PAListPtr &PAL = F->getParamAttrs();
2167 std::stringstream FunctionInnards;
2169 // Print out the name...
2170 FunctionInnards << GetValueName(F) << '(';
2172 bool PrintedArg = false;
2173 if (!F->isDeclaration()) {
2174 if (!F->arg_empty()) {
2175 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2178 // If this is a struct-return function, don't print the hidden
2179 // struct-return argument.
2180 if (isStructReturn) {
2181 assert(I != E && "Invalid struct return function!");
2186 std::string ArgName;
2187 for (; I != E; ++I) {
2188 if (PrintedArg) FunctionInnards << ", ";
2189 if (I->hasName() || !Prototype)
2190 ArgName = GetValueName(I);
2193 const Type *ArgTy = I->getType();
2194 if (PAL.paramHasAttr(Idx, ParamAttr::ByVal)) {
2195 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2196 ByValParams.insert(I);
2198 printType(FunctionInnards, ArgTy,
2199 /*isSigned=*/PAL.paramHasAttr(Idx, ParamAttr::SExt),
2206 // Loop over the arguments, printing them.
2207 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
2210 // If this is a struct-return function, don't print the hidden
2211 // struct-return argument.
2212 if (isStructReturn) {
2213 assert(I != E && "Invalid struct return function!");
2218 for (; I != E; ++I) {
2219 if (PrintedArg) FunctionInnards << ", ";
2220 const Type *ArgTy = *I;
2221 if (PAL.paramHasAttr(Idx, ParamAttr::ByVal)) {
2222 assert(isa<PointerType>(ArgTy));
2223 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2225 printType(FunctionInnards, ArgTy,
2226 /*isSigned=*/PAL.paramHasAttr(Idx, ParamAttr::SExt));
2232 // Finish printing arguments... if this is a vararg function, print the ...,
2233 // unless there are no known types, in which case, we just emit ().
2235 if (FT->isVarArg() && PrintedArg) {
2236 if (PrintedArg) FunctionInnards << ", ";
2237 FunctionInnards << "..."; // Output varargs portion of signature!
2238 } else if (!FT->isVarArg() && !PrintedArg) {
2239 FunctionInnards << "void"; // ret() -> ret(void) in C.
2241 FunctionInnards << ')';
2243 // Get the return tpe for the function.
2245 if (!isStructReturn)
2246 RetTy = F->getReturnType();
2248 // If this is a struct-return function, print the struct-return type.
2249 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2252 // Print out the return type and the signature built above.
2253 printType(Out, RetTy,
2254 /*isSigned=*/PAL.paramHasAttr(0, ParamAttr::SExt),
2255 FunctionInnards.str());
2258 static inline bool isFPIntBitCast(const Instruction &I) {
2259 if (!isa<BitCastInst>(I))
2261 const Type *SrcTy = I.getOperand(0)->getType();
2262 const Type *DstTy = I.getType();
2263 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2264 (DstTy->isFloatingPoint() && SrcTy->isInteger());
2267 void CWriter::printFunction(Function &F) {
2268 /// isStructReturn - Should this function actually return a struct by-value?
2269 bool isStructReturn = F.hasStructRetAttr();
2271 printFunctionSignature(&F, false);
2274 // If this is a struct return function, handle the result with magic.
2275 if (isStructReturn) {
2276 const Type *StructTy =
2277 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2279 printType(Out, StructTy, false, "StructReturn");
2280 Out << "; /* Struct return temporary */\n";
2283 printType(Out, F.arg_begin()->getType(), false,
2284 GetValueName(F.arg_begin()));
2285 Out << " = &StructReturn;\n";
2288 bool PrintedVar = false;
2290 // print local variable information for the function
2291 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2292 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2294 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2295 Out << "; /* Address-exposed local */\n";
2297 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
2299 printType(Out, I->getType(), false, GetValueName(&*I));
2302 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2304 printType(Out, I->getType(), false,
2305 GetValueName(&*I)+"__PHI_TEMPORARY");
2310 // We need a temporary for the BitCast to use so it can pluck a value out
2311 // of a union to do the BitCast. This is separate from the need for a
2312 // variable to hold the result of the BitCast.
2313 if (isFPIntBitCast(*I)) {
2314 Out << " llvmBitCastUnion " << GetValueName(&*I)
2315 << "__BITCAST_TEMPORARY;\n";
2323 if (F.hasExternalLinkage() && F.getName() == "main")
2324 Out << " CODE_FOR_MAIN();\n";
2326 // print the basic blocks
2327 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2328 if (Loop *L = LI->getLoopFor(BB)) {
2329 if (L->getHeader() == BB && L->getParentLoop() == 0)
2332 printBasicBlock(BB);
2339 void CWriter::printLoop(Loop *L) {
2340 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2341 << "' to make GCC happy */\n";
2342 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2343 BasicBlock *BB = L->getBlocks()[i];
2344 Loop *BBLoop = LI->getLoopFor(BB);
2346 printBasicBlock(BB);
2347 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2350 Out << " } while (1); /* end of syntactic loop '"
2351 << L->getHeader()->getName() << "' */\n";
2354 void CWriter::printBasicBlock(BasicBlock *BB) {
2356 // Don't print the label for the basic block if there are no uses, or if
2357 // the only terminator use is the predecessor basic block's terminator.
2358 // We have to scan the use list because PHI nodes use basic blocks too but
2359 // do not require a label to be generated.
2361 bool NeedsLabel = false;
2362 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2363 if (isGotoCodeNecessary(*PI, BB)) {
2368 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2370 // Output all of the instructions in the basic block...
2371 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2373 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2374 if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
2378 writeInstComputationInline(*II);
2383 // Don't emit prefix or suffix for the terminator.
2384 visit(*BB->getTerminator());
2388 // Specific Instruction type classes... note that all of the casts are
2389 // necessary because we use the instruction classes as opaque types...
2391 void CWriter::visitReturnInst(ReturnInst &I) {
2392 // If this is a struct return function, return the temporary struct.
2393 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
2395 if (isStructReturn) {
2396 Out << " return StructReturn;\n";
2400 // Don't output a void return if this is the last basic block in the function
2401 if (I.getNumOperands() == 0 &&
2402 &*--I.getParent()->getParent()->end() == I.getParent() &&
2403 !I.getParent()->size() == 1) {
2407 if (I.getNumOperands() > 1) {
2410 printType(Out, I.getParent()->getParent()->getReturnType());
2411 Out << " llvm_cbe_mrv_temp = {\n";
2412 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2414 writeOperand(I.getOperand(i));
2420 Out << " return llvm_cbe_mrv_temp;\n";
2426 if (I.getNumOperands()) {
2428 writeOperand(I.getOperand(0));
2433 void CWriter::visitSwitchInst(SwitchInst &SI) {
2436 writeOperand(SI.getOperand(0));
2437 Out << ") {\n default:\n";
2438 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2439 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2441 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2443 writeOperand(SI.getOperand(i));
2445 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2446 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2447 printBranchToBlock(SI.getParent(), Succ, 2);
2448 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
2454 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2455 Out << " /*UNREACHABLE*/;\n";
2458 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2459 /// FIXME: This should be reenabled, but loop reordering safe!!
2462 if (next(Function::iterator(From)) != Function::iterator(To))
2463 return true; // Not the direct successor, we need a goto.
2465 //isa<SwitchInst>(From->getTerminator())
2467 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2472 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2473 BasicBlock *Successor,
2475 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2476 PHINode *PN = cast<PHINode>(I);
2477 // Now we have to do the printing.
2478 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2479 if (!isa<UndefValue>(IV)) {
2480 Out << std::string(Indent, ' ');
2481 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2483 Out << "; /* for PHI node */\n";
2488 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2490 if (isGotoCodeNecessary(CurBB, Succ)) {
2491 Out << std::string(Indent, ' ') << " goto ";
2497 // Branch instruction printing - Avoid printing out a branch to a basic block
2498 // that immediately succeeds the current one.
2500 void CWriter::visitBranchInst(BranchInst &I) {
2502 if (I.isConditional()) {
2503 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2505 writeOperand(I.getCondition());
2508 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2509 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2511 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2512 Out << " } else {\n";
2513 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2514 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2517 // First goto not necessary, assume second one is...
2519 writeOperand(I.getCondition());
2522 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2523 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2528 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2529 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2534 // PHI nodes get copied into temporary values at the end of predecessor basic
2535 // blocks. We now need to copy these temporary values into the REAL value for
2537 void CWriter::visitPHINode(PHINode &I) {
2539 Out << "__PHI_TEMPORARY";
2543 void CWriter::visitBinaryOperator(Instruction &I) {
2544 // binary instructions, shift instructions, setCond instructions.
2545 assert(!isa<PointerType>(I.getType()));
2547 // We must cast the results of binary operations which might be promoted.
2548 bool needsCast = false;
2549 if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty)
2550 || (I.getType() == Type::FloatTy)) {
2553 printType(Out, I.getType(), false);
2557 // If this is a negation operation, print it out as such. For FP, we don't
2558 // want to print "-0.0 - X".
2559 if (BinaryOperator::isNeg(&I)) {
2561 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2563 } else if (I.getOpcode() == Instruction::FRem) {
2564 // Output a call to fmod/fmodf instead of emitting a%b
2565 if (I.getType() == Type::FloatTy)
2567 else if (I.getType() == Type::DoubleTy)
2569 else // all 3 flavors of long double
2571 writeOperand(I.getOperand(0));
2573 writeOperand(I.getOperand(1));
2577 // Write out the cast of the instruction's value back to the proper type
2579 bool NeedsClosingParens = writeInstructionCast(I);
2581 // Certain instructions require the operand to be forced to a specific type
2582 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2583 // below for operand 1
2584 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2586 switch (I.getOpcode()) {
2587 case Instruction::Add: Out << " + "; break;
2588 case Instruction::Sub: Out << " - "; break;
2589 case Instruction::Mul: Out << " * "; break;
2590 case Instruction::URem:
2591 case Instruction::SRem:
2592 case Instruction::FRem: Out << " % "; break;
2593 case Instruction::UDiv:
2594 case Instruction::SDiv:
2595 case Instruction::FDiv: Out << " / "; break;
2596 case Instruction::And: Out << " & "; break;
2597 case Instruction::Or: Out << " | "; break;
2598 case Instruction::Xor: Out << " ^ "; break;
2599 case Instruction::Shl : Out << " << "; break;
2600 case Instruction::LShr:
2601 case Instruction::AShr: Out << " >> "; break;
2602 default: cerr << "Invalid operator type!" << I; abort();
2605 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2606 if (NeedsClosingParens)
2615 void CWriter::visitICmpInst(ICmpInst &I) {
2616 // We must cast the results of icmp which might be promoted.
2617 bool needsCast = false;
2619 // Write out the cast of the instruction's value back to the proper type
2621 bool NeedsClosingParens = writeInstructionCast(I);
2623 // Certain icmp predicate require the operand to be forced to a specific type
2624 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2625 // below for operand 1
2626 writeOperandWithCast(I.getOperand(0), I);
2628 switch (I.getPredicate()) {
2629 case ICmpInst::ICMP_EQ: Out << " == "; break;
2630 case ICmpInst::ICMP_NE: Out << " != "; break;
2631 case ICmpInst::ICMP_ULE:
2632 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2633 case ICmpInst::ICMP_UGE:
2634 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2635 case ICmpInst::ICMP_ULT:
2636 case ICmpInst::ICMP_SLT: Out << " < "; break;
2637 case ICmpInst::ICMP_UGT:
2638 case ICmpInst::ICMP_SGT: Out << " > "; break;
2639 default: cerr << "Invalid icmp predicate!" << I; abort();
2642 writeOperandWithCast(I.getOperand(1), I);
2643 if (NeedsClosingParens)
2651 void CWriter::visitFCmpInst(FCmpInst &I) {
2652 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2656 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2662 switch (I.getPredicate()) {
2663 default: assert(0 && "Illegal FCmp predicate");
2664 case FCmpInst::FCMP_ORD: op = "ord"; break;
2665 case FCmpInst::FCMP_UNO: op = "uno"; break;
2666 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2667 case FCmpInst::FCMP_UNE: op = "une"; break;
2668 case FCmpInst::FCMP_ULT: op = "ult"; break;
2669 case FCmpInst::FCMP_ULE: op = "ule"; break;
2670 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2671 case FCmpInst::FCMP_UGE: op = "uge"; break;
2672 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2673 case FCmpInst::FCMP_ONE: op = "one"; break;
2674 case FCmpInst::FCMP_OLT: op = "olt"; break;
2675 case FCmpInst::FCMP_OLE: op = "ole"; break;
2676 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2677 case FCmpInst::FCMP_OGE: op = "oge"; break;
2680 Out << "llvm_fcmp_" << op << "(";
2681 // Write the first operand
2682 writeOperand(I.getOperand(0));
2684 // Write the second operand
2685 writeOperand(I.getOperand(1));
2689 static const char * getFloatBitCastField(const Type *Ty) {
2690 switch (Ty->getTypeID()) {
2691 default: assert(0 && "Invalid Type");
2692 case Type::FloatTyID: return "Float";
2693 case Type::DoubleTyID: return "Double";
2694 case Type::IntegerTyID: {
2695 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2704 void CWriter::visitCastInst(CastInst &I) {
2705 const Type *DstTy = I.getType();
2706 const Type *SrcTy = I.getOperand(0)->getType();
2707 if (isFPIntBitCast(I)) {
2709 // These int<->float and long<->double casts need to be handled specially
2710 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2711 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2712 writeOperand(I.getOperand(0));
2713 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2714 << getFloatBitCastField(I.getType());
2720 printCast(I.getOpcode(), SrcTy, DstTy);
2722 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
2723 if (SrcTy == Type::Int1Ty && I.getOpcode() == Instruction::SExt)
2726 writeOperand(I.getOperand(0));
2728 if (DstTy == Type::Int1Ty &&
2729 (I.getOpcode() == Instruction::Trunc ||
2730 I.getOpcode() == Instruction::FPToUI ||
2731 I.getOpcode() == Instruction::FPToSI ||
2732 I.getOpcode() == Instruction::PtrToInt)) {
2733 // Make sure we really get a trunc to bool by anding the operand with 1
2739 void CWriter::visitSelectInst(SelectInst &I) {
2741 writeOperand(I.getCondition());
2743 writeOperand(I.getTrueValue());
2745 writeOperand(I.getFalseValue());
2750 void CWriter::lowerIntrinsics(Function &F) {
2751 // This is used to keep track of intrinsics that get generated to a lowered
2752 // function. We must generate the prototypes before the function body which
2753 // will only be expanded on first use (by the loop below).
2754 std::vector<Function*> prototypesToGen;
2756 // Examine all the instructions in this function to find the intrinsics that
2757 // need to be lowered.
2758 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2759 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2760 if (CallInst *CI = dyn_cast<CallInst>(I++))
2761 if (Function *F = CI->getCalledFunction())
2762 switch (F->getIntrinsicID()) {
2763 case Intrinsic::not_intrinsic:
2764 case Intrinsic::memory_barrier:
2765 case Intrinsic::vastart:
2766 case Intrinsic::vacopy:
2767 case Intrinsic::vaend:
2768 case Intrinsic::returnaddress:
2769 case Intrinsic::frameaddress:
2770 case Intrinsic::setjmp:
2771 case Intrinsic::longjmp:
2772 case Intrinsic::prefetch:
2773 case Intrinsic::dbg_stoppoint:
2774 case Intrinsic::powi:
2775 case Intrinsic::x86_sse_cmp_ss:
2776 case Intrinsic::x86_sse_cmp_ps:
2777 case Intrinsic::x86_sse2_cmp_sd:
2778 case Intrinsic::x86_sse2_cmp_pd:
2779 case Intrinsic::ppc_altivec_lvsl:
2780 // We directly implement these intrinsics
2783 // If this is an intrinsic that directly corresponds to a GCC
2784 // builtin, we handle it.
2785 const char *BuiltinName = "";
2786 #define GET_GCC_BUILTIN_NAME
2787 #include "llvm/Intrinsics.gen"
2788 #undef GET_GCC_BUILTIN_NAME
2789 // If we handle it, don't lower it.
2790 if (BuiltinName[0]) break;
2792 // All other intrinsic calls we must lower.
2793 Instruction *Before = 0;
2794 if (CI != &BB->front())
2795 Before = prior(BasicBlock::iterator(CI));
2797 IL->LowerIntrinsicCall(CI);
2798 if (Before) { // Move iterator to instruction after call
2803 // If the intrinsic got lowered to another call, and that call has
2804 // a definition then we need to make sure its prototype is emitted
2805 // before any calls to it.
2806 if (CallInst *Call = dyn_cast<CallInst>(I))
2807 if (Function *NewF = Call->getCalledFunction())
2808 if (!NewF->isDeclaration())
2809 prototypesToGen.push_back(NewF);
2814 // We may have collected some prototypes to emit in the loop above.
2815 // Emit them now, before the function that uses them is emitted. But,
2816 // be careful not to emit them twice.
2817 std::vector<Function*>::iterator I = prototypesToGen.begin();
2818 std::vector<Function*>::iterator E = prototypesToGen.end();
2819 for ( ; I != E; ++I) {
2820 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2822 printFunctionSignature(*I, true);
2828 void CWriter::visitCallInst(CallInst &I) {
2829 if (isa<InlineAsm>(I.getOperand(0)))
2830 return visitInlineAsm(I);
2832 bool WroteCallee = false;
2834 // Handle intrinsic function calls first...
2835 if (Function *F = I.getCalledFunction())
2836 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2837 if (visitBuiltinCall(I, ID, WroteCallee))
2840 Value *Callee = I.getCalledValue();
2842 const PointerType *PTy = cast<PointerType>(Callee->getType());
2843 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2845 // If this is a call to a struct-return function, assign to the first
2846 // parameter instead of passing it to the call.
2847 const PAListPtr &PAL = I.getParamAttrs();
2848 bool hasByVal = I.hasByValArgument();
2849 bool isStructRet = I.hasStructRetAttr();
2851 writeOperandDeref(I.getOperand(1));
2855 if (I.isTailCall()) Out << " /*tail*/ ";
2858 // If this is an indirect call to a struct return function, we need to cast
2859 // the pointer. Ditto for indirect calls with byval arguments.
2860 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
2862 // GCC is a real PITA. It does not permit codegening casts of functions to
2863 // function pointers if they are in a call (it generates a trap instruction
2864 // instead!). We work around this by inserting a cast to void* in between
2865 // the function and the function pointer cast. Unfortunately, we can't just
2866 // form the constant expression here, because the folder will immediately
2869 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2870 // that void* and function pointers have the same size. :( To deal with this
2871 // in the common case, we handle casts where the number of arguments passed
2874 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2876 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2882 // Ok, just cast the pointer type.
2885 printStructReturnPointerFunctionType(Out, PAL,
2886 cast<PointerType>(I.getCalledValue()->getType()));
2888 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
2890 printType(Out, I.getCalledValue()->getType());
2893 writeOperand(Callee);
2894 if (NeedsCast) Out << ')';
2899 unsigned NumDeclaredParams = FTy->getNumParams();
2901 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2903 if (isStructRet) { // Skip struct return argument.
2908 bool PrintedArg = false;
2909 for (; AI != AE; ++AI, ++ArgNo) {
2910 if (PrintedArg) Out << ", ";
2911 if (ArgNo < NumDeclaredParams &&
2912 (*AI)->getType() != FTy->getParamType(ArgNo)) {
2914 printType(Out, FTy->getParamType(ArgNo),
2915 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, ParamAttr::SExt));
2918 // Check if the argument is expected to be passed by value.
2919 if (I.paramHasAttr(ArgNo+1, ParamAttr::ByVal))
2920 writeOperandDeref(*AI);
2928 /// visitBuiltinCall - Handle the call to the specified builtin. Returns true
2929 /// if the entire call is handled, return false it it wasn't handled, and
2930 /// optionally set 'WroteCallee' if the callee has already been printed out.
2931 bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
2932 bool &WroteCallee) {
2935 // If this is an intrinsic that directly corresponds to a GCC
2936 // builtin, we emit it here.
2937 const char *BuiltinName = "";
2938 Function *F = I.getCalledFunction();
2939 #define GET_GCC_BUILTIN_NAME
2940 #include "llvm/Intrinsics.gen"
2941 #undef GET_GCC_BUILTIN_NAME
2942 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2948 case Intrinsic::memory_barrier:
2949 Out << "__sync_synchronize()";
2951 case Intrinsic::vastart:
2954 Out << "va_start(*(va_list*)";
2955 writeOperand(I.getOperand(1));
2957 // Output the last argument to the enclosing function.
2958 if (I.getParent()->getParent()->arg_empty()) {
2959 cerr << "The C backend does not currently support zero "
2960 << "argument varargs functions, such as '"
2961 << I.getParent()->getParent()->getName() << "'!\n";
2964 writeOperand(--I.getParent()->getParent()->arg_end());
2967 case Intrinsic::vaend:
2968 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
2969 Out << "0; va_end(*(va_list*)";
2970 writeOperand(I.getOperand(1));
2973 Out << "va_end(*(va_list*)0)";
2976 case Intrinsic::vacopy:
2978 Out << "va_copy(*(va_list*)";
2979 writeOperand(I.getOperand(1));
2980 Out << ", *(va_list*)";
2981 writeOperand(I.getOperand(2));
2984 case Intrinsic::returnaddress:
2985 Out << "__builtin_return_address(";
2986 writeOperand(I.getOperand(1));
2989 case Intrinsic::frameaddress:
2990 Out << "__builtin_frame_address(";
2991 writeOperand(I.getOperand(1));
2994 case Intrinsic::powi:
2995 Out << "__builtin_powi(";
2996 writeOperand(I.getOperand(1));
2998 writeOperand(I.getOperand(2));
3001 case Intrinsic::setjmp:
3002 Out << "setjmp(*(jmp_buf*)";
3003 writeOperand(I.getOperand(1));
3006 case Intrinsic::longjmp:
3007 Out << "longjmp(*(jmp_buf*)";
3008 writeOperand(I.getOperand(1));
3010 writeOperand(I.getOperand(2));
3013 case Intrinsic::prefetch:
3014 Out << "LLVM_PREFETCH((const void *)";
3015 writeOperand(I.getOperand(1));
3017 writeOperand(I.getOperand(2));
3019 writeOperand(I.getOperand(3));
3022 case Intrinsic::stacksave:
3023 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3024 // to work around GCC bugs (see PR1809).
3025 Out << "0; *((void**)&" << GetValueName(&I)
3026 << ") = __builtin_stack_save()";
3028 case Intrinsic::dbg_stoppoint: {
3029 // If we use writeOperand directly we get a "u" suffix which is rejected
3031 std::stringstream SPIStr;
3032 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3033 SPI.getDirectory()->print(SPIStr);
3037 Out << SPIStr.str();
3039 SPI.getFileName()->print(SPIStr);
3040 Out << SPIStr.str() << "\"\n";
3043 case Intrinsic::x86_sse_cmp_ss:
3044 case Intrinsic::x86_sse_cmp_ps:
3045 case Intrinsic::x86_sse2_cmp_sd:
3046 case Intrinsic::x86_sse2_cmp_pd:
3048 printType(Out, I.getType());
3050 // Multiple GCC builtins multiplex onto this intrinsic.
3051 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
3052 default: assert(0 && "Invalid llvm.x86.sse.cmp!");
3053 case 0: Out << "__builtin_ia32_cmpeq"; break;
3054 case 1: Out << "__builtin_ia32_cmplt"; break;
3055 case 2: Out << "__builtin_ia32_cmple"; break;
3056 case 3: Out << "__builtin_ia32_cmpunord"; break;
3057 case 4: Out << "__builtin_ia32_cmpneq"; break;
3058 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3059 case 6: Out << "__builtin_ia32_cmpnle"; break;
3060 case 7: Out << "__builtin_ia32_cmpord"; break;
3062 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3066 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3072 writeOperand(I.getOperand(1));
3074 writeOperand(I.getOperand(2));
3077 case Intrinsic::ppc_altivec_lvsl:
3079 printType(Out, I.getType());
3081 Out << "__builtin_altivec_lvsl(0, (void*)";
3082 writeOperand(I.getOperand(1));
3088 //This converts the llvm constraint string to something gcc is expecting.
3089 //TODO: work out platform independent constraints and factor those out
3090 // of the per target tables
3091 // handle multiple constraint codes
3092 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
3094 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3096 const char *const *table = 0;
3098 //Grab the translation table from TargetAsmInfo if it exists
3101 const TargetMachineRegistry::entry* Match =
3102 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
3104 //Per platform Target Machines don't exist, so create it
3105 // this must be done only once
3106 const TargetMachine* TM = Match->CtorFn(*TheModule, "");
3107 TAsm = TM->getTargetAsmInfo();
3111 table = TAsm->getAsmCBE();
3113 //Search the translation table if it exists
3114 for (int i = 0; table && table[i]; i += 2)
3115 if (c.Codes[0] == table[i])
3118 //default is identity
3122 //TODO: import logic from AsmPrinter.cpp
3123 static std::string gccifyAsm(std::string asmstr) {
3124 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3125 if (asmstr[i] == '\n')
3126 asmstr.replace(i, 1, "\\n");
3127 else if (asmstr[i] == '\t')
3128 asmstr.replace(i, 1, "\\t");
3129 else if (asmstr[i] == '$') {
3130 if (asmstr[i + 1] == '{') {
3131 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3132 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3133 std::string n = "%" +
3134 asmstr.substr(a + 1, b - a - 1) +
3135 asmstr.substr(i + 2, a - i - 2);
3136 asmstr.replace(i, b - i + 1, n);
3139 asmstr.replace(i, 1, "%");
3141 else if (asmstr[i] == '%')//grr
3142 { asmstr.replace(i, 1, "%%"); ++i;}
3147 //TODO: assumptions about what consume arguments from the call are likely wrong
3148 // handle communitivity
3149 void CWriter::visitInlineAsm(CallInst &CI) {
3150 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
3151 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
3153 std::vector<std::pair<Value*, int> > ResultVals;
3154 if (CI.getType() == Type::VoidTy)
3156 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3157 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3158 ResultVals.push_back(std::make_pair(&CI, (int)i));
3160 ResultVals.push_back(std::make_pair(&CI, -1));
3163 // Fix up the asm string for gcc and emit it.
3164 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3167 unsigned ValueCount = 0;
3168 bool IsFirst = true;
3170 // Convert over all the output constraints.
3171 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3172 E = Constraints.end(); I != E; ++I) {
3174 if (I->Type != InlineAsm::isOutput) {
3176 continue; // Ignore non-output constraints.
3179 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3180 std::string C = InterpretASMConstraint(*I);
3181 if (C.empty()) continue;
3192 if (ValueCount < ResultVals.size()) {
3193 DestVal = ResultVals[ValueCount].first;
3194 DestValNo = ResultVals[ValueCount].second;
3196 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3198 if (I->isEarlyClobber)
3201 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3202 if (DestValNo != -1)
3203 Out << ".field" << DestValNo; // Multiple retvals.
3209 // Convert over all the input constraints.
3213 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3214 E = Constraints.end(); I != E; ++I) {
3215 if (I->Type != InlineAsm::isInput) {
3217 continue; // Ignore non-input constraints.
3220 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3221 std::string C = InterpretASMConstraint(*I);
3222 if (C.empty()) continue;
3229 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3230 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3232 Out << "\"" << C << "\"(";
3234 writeOperand(SrcVal);
3236 writeOperandDeref(SrcVal);
3240 // Convert over the clobber constraints.
3243 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3244 E = Constraints.end(); I != E; ++I) {
3245 if (I->Type != InlineAsm::isClobber)
3246 continue; // Ignore non-input constraints.
3248 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3249 std::string C = InterpretASMConstraint(*I);
3250 if (C.empty()) continue;
3257 Out << '\"' << C << '"';
3263 void CWriter::visitMallocInst(MallocInst &I) {
3264 assert(0 && "lowerallocations pass didn't work!");
3267 void CWriter::visitAllocaInst(AllocaInst &I) {
3269 printType(Out, I.getType());
3270 Out << ") alloca(sizeof(";
3271 printType(Out, I.getType()->getElementType());
3273 if (I.isArrayAllocation()) {
3275 writeOperand(I.getOperand(0));
3280 void CWriter::visitFreeInst(FreeInst &I) {
3281 assert(0 && "lowerallocations pass didn't work!");
3284 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
3285 gep_type_iterator E, bool Static) {
3287 // If there are no indices, just print out the pointer.
3293 // Find out if the last index is into a vector. If so, we have to print this
3294 // specially. Since vectors can't have elements of indexable type, only the
3295 // last index could possibly be of a vector element.
3296 const VectorType *LastIndexIsVector = 0;
3298 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3299 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
3304 // If the last index is into a vector, we can't print it as &a[i][j] because
3305 // we can't index into a vector with j in GCC. Instead, emit this as
3306 // (((float*)&a[i])+j)
3307 if (LastIndexIsVector) {
3309 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3315 // If the first index is 0 (very typical) we can do a number of
3316 // simplifications to clean up the code.
3317 Value *FirstOp = I.getOperand();
3318 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3319 // First index isn't simple, print it the hard way.
3322 ++I; // Skip the zero index.
3324 // Okay, emit the first operand. If Ptr is something that is already address
3325 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3326 if (isAddressExposed(Ptr)) {
3327 writeOperandInternal(Ptr, Static);
3328 } else if (I != E && isa<StructType>(*I)) {
3329 // If we didn't already emit the first operand, see if we can print it as
3330 // P->f instead of "P[0].f"
3332 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3333 ++I; // eat the struct index as well.
3335 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3342 for (; I != E; ++I) {
3343 if (isa<StructType>(*I)) {
3344 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3345 } else if (isa<ArrayType>(*I)) {
3347 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3349 } else if (!isa<VectorType>(*I)) {
3351 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3354 // If the last index is into a vector, then print it out as "+j)". This
3355 // works with the 'LastIndexIsVector' code above.
3356 if (isa<Constant>(I.getOperand()) &&
3357 cast<Constant>(I.getOperand())->isNullValue()) {
3358 Out << "))"; // avoid "+0".
3361 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3369 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3370 bool IsVolatile, unsigned Alignment) {
3372 bool IsUnaligned = Alignment &&
3373 Alignment < TD->getABITypeAlignment(OperandType);
3377 if (IsVolatile || IsUnaligned) {
3380 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3381 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3384 if (IsVolatile) Out << "volatile ";
3390 writeOperand(Operand);
3392 if (IsVolatile || IsUnaligned) {
3399 void CWriter::visitLoadInst(LoadInst &I) {
3400 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3405 void CWriter::visitStoreInst(StoreInst &I) {
3406 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3407 I.isVolatile(), I.getAlignment());
3409 Value *Operand = I.getOperand(0);
3410 Constant *BitMask = 0;
3411 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3412 if (!ITy->isPowerOf2ByteWidth())
3413 // We have a bit width that doesn't match an even power-of-2 byte
3414 // size. Consequently we must & the value with the type's bit mask
3415 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
3418 writeOperand(Operand);
3421 printConstant(BitMask, false);
3426 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
3427 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
3428 gep_type_end(I), false);
3431 void CWriter::visitVAArgInst(VAArgInst &I) {
3432 Out << "va_arg(*(va_list*)";
3433 writeOperand(I.getOperand(0));
3435 printType(Out, I.getType());
3439 void CWriter::visitInsertElementInst(InsertElementInst &I) {
3440 const Type *EltTy = I.getType()->getElementType();
3441 writeOperand(I.getOperand(0));
3444 printType(Out, PointerType::getUnqual(EltTy));
3445 Out << ")(&" << GetValueName(&I) << "))[";
3446 writeOperand(I.getOperand(2));
3448 writeOperand(I.getOperand(1));
3452 void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3453 // We know that our operand is not inlined.
3456 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3457 printType(Out, PointerType::getUnqual(EltTy));
3458 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3459 writeOperand(I.getOperand(1));
3463 void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3465 printType(Out, SVI.getType());
3467 const VectorType *VT = SVI.getType();
3468 unsigned NumElts = VT->getNumElements();
3469 const Type *EltTy = VT->getElementType();
3471 for (unsigned i = 0; i != NumElts; ++i) {
3473 int SrcVal = SVI.getMaskValue(i);
3474 if ((unsigned)SrcVal >= NumElts*2) {
3475 Out << " 0/*undef*/ ";
3477 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3478 if (isa<Instruction>(Op)) {
3479 // Do an extractelement of this value from the appropriate input.
3481 printType(Out, PointerType::getUnqual(EltTy));
3482 Out << ")(&" << GetValueName(Op)
3483 << "))[" << (SrcVal & (NumElts-1)) << "]";
3484 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3487 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
3496 void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3497 // Start by copying the entire aggregate value into the result variable.
3498 writeOperand(IVI.getOperand(0));
3501 // Then do the insert to update the field.
3502 Out << GetValueName(&IVI);
3503 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3505 const Type *IndexedTy =
3506 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3507 if (isa<ArrayType>(IndexedTy))
3508 Out << ".array[" << *i << "]";
3510 Out << ".field" << *i;
3513 writeOperand(IVI.getOperand(1));
3516 void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3518 if (isa<UndefValue>(EVI.getOperand(0))) {
3520 printType(Out, EVI.getType());
3521 Out << ") 0/*UNDEF*/";
3523 Out << GetValueName(EVI.getOperand(0));
3524 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3526 const Type *IndexedTy =
3527 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3528 if (isa<ArrayType>(IndexedTy))
3529 Out << ".array[" << *i << "]";
3531 Out << ".field" << *i;
3537 //===----------------------------------------------------------------------===//
3538 // External Interface declaration
3539 //===----------------------------------------------------------------------===//
3541 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
3543 CodeGenFileType FileType,
3545 if (FileType != TargetMachine::AssemblyFile) return true;
3547 PM.add(createGCLoweringPass());
3548 PM.add(createLowerAllocationsPass(true));
3549 PM.add(createLowerInvokePass());
3550 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3551 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3552 PM.add(new CWriter(o));
3553 PM.add(createGCInfoDeleter());