Revise previous patch per review comments.
[oota-llvm.git] / lib / Target / CBackend / CBackend.cpp
index b434d31b90a8b6ad140e515d8a563992ba7f07b5..9fc30c45da1405e9d9e0e0e5632fa18c3bbd5e5a 100644 (file)
@@ -18,6 +18,7 @@
 #include "llvm/DerivedTypes.h"
 #include "llvm/Module.h"
 #include "llvm/Instructions.h"
+#include "llvm/ParameterAttributes.h"
 #include "llvm/Pass.h"
 #include "llvm/PassManager.h"
 #include "llvm/TypeSymbolTable.h"
@@ -55,6 +56,10 @@ namespace {
   /// external functions with the same name.
   ///
   class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
+  public:
+    static char ID;
+    CBackendNameAllUsedStructsAndMergeFunctions() 
+      : ModulePass((intptr_t)&ID) {}
     void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.addRequired<FindUsedTypes>();
     }
@@ -66,6 +71,8 @@ namespace {
     virtual bool runOnModule(Module &M);
   };
 
+  char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
+
   /// CWriter - This class is the main chunk of code that converts an LLVM
   /// module to a C translation unit.
   class CWriter : public FunctionPass, public InstVisitor<CWriter> {
@@ -77,11 +84,14 @@ namespace {
     const TargetAsmInfo* TAsm;
     const TargetData* TD;
     std::map<const Type *, std::string> TypeNames;
-
     std::map<const ConstantFP *, unsigned> FPConstantMap;
+    std::set<Function*> intrinsicPrototypesAlreadyGenerated;
+
   public:
-    CWriter(std::ostream &o) : Out(o), IL(0), Mang(0), LI(0), TheModule(0), 
-                               TAsm(0), TD(0) {}
+    static char ID;
+    CWriter(std::ostream &o) 
+      : FunctionPass((intptr_t)&ID), Out(o), IL(0), Mang(0), LI(0), 
+        TheModule(0), TAsm(0), TD(0) {}
 
     virtual const char *getPassName() const { return "C backend"; }
 
@@ -239,7 +249,7 @@ namespace {
     }
 
     void outputLValue(Instruction *I) {
-      Out << "  " << Mang->getValueName(I) << " = ";
+      Out << "  " << GetValueName(I) << " = ";
     }
 
     bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
@@ -249,9 +259,13 @@ namespace {
                             unsigned Indent);
     void printIndexingExpression(Value *Ptr, gep_type_iterator I,
                                  gep_type_iterator E);
+
+    std::string GetValueName(const Value *Operand);
   };
 }
 
+char CWriter::ID = 0;
+
 /// This method inserts names for any unnamed structure types that are used by
 /// the program, and removes names from structure types that are not used by the
 /// program.
@@ -348,11 +362,12 @@ void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
   FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
   const Type *RetTy = cast<PointerType>(I->get())->getElementType();
   unsigned Idx = 1;
+  const ParamAttrsList *Attrs = FTy->getParamAttrs();
   for (++I; I != E; ++I) {
     if (PrintedType)
       FunctionInnards << ", ";
     printType(FunctionInnards, *I, 
-        /*isSigned=*/FTy->paramHasAttr(Idx, FunctionType::SExtAttribute), "");
+        /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt), "");
     PrintedType = true;
   }
   if (FTy->isVarArg()) {
@@ -364,7 +379,7 @@ void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
   FunctionInnards << ')';
   std::string tstr = FunctionInnards.str();
   printType(Out, RetTy, 
-      /*isSigned=*/FTy->paramHasAttr(0, FunctionType::SExtAttribute), tstr);
+      /*isSigned=*/Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt), tstr);
 }
 
 std::ostream &
@@ -419,13 +434,14 @@ std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
     const FunctionType *FTy = cast<FunctionType>(Ty);
     std::stringstream FunctionInnards;
     FunctionInnards << " (" << NameSoFar << ") (";
+    const ParamAttrsList *Attrs = FTy->getParamAttrs();
     unsigned Idx = 1;
     for (FunctionType::param_iterator I = FTy->param_begin(),
            E = FTy->param_end(); I != E; ++I) {
       if (I != FTy->param_begin())
         FunctionInnards << ", ";
       printType(FunctionInnards, *I, 
-         /*isSigned=*/FTy->paramHasAttr(Idx, FunctionType::SExtAttribute), "");
+         /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt), "");
       ++Idx;
     }
     if (FTy->isVarArg()) {
@@ -437,7 +453,7 @@ std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
     FunctionInnards << ')';
     std::string tstr = FunctionInnards.str();
     printType(Out, FTy->getReturnType(), 
-        /*isSigned=*/FTy->paramHasAttr(0, FunctionType::SExtAttribute), tstr);
+        /*isSigned=*/Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt), tstr);
     return Out;
   }
   case Type::StructTyID: {
@@ -450,7 +466,10 @@ std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
       printType(Out, *I, false, "field" + utostr(Idx++));
       Out << ";\n";
     }
-    return Out << '}';
+    Out << '}';
+    if (STy->isPacked())
+      Out << " __attribute__ ((packed))";
+    return Out;
   }
 
   case Type::PointerTyID: {
@@ -585,17 +604,19 @@ void CWriter::printConstantVector(ConstantVector *CP) {
 // only deal in IEEE FP).
 //
 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
+  APFloat APF = APFloat(CFP->getValueAPF());  // copy
+  if (CFP->getType()==Type::FloatTy)
+    APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
   char Buffer[100];
-  sprintf(Buffer, "%a", CFP->getValue());
-
+  sprintf(Buffer, "%a", APF.convertToDouble());
   if (!strncmp(Buffer, "0x", 2) ||
       !strncmp(Buffer, "-0x", 3) ||
       !strncmp(Buffer, "+0x", 3))
-    return atof(Buffer) == CFP->getValue();
+    return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
   return false;
 #else
-  std::string StrVal = ftostr(CFP->getValue());
+  std::string StrVal = ftostr(APF);
 
   while (StrVal[0] == ' ')
     StrVal.erase(StrVal.begin());
@@ -606,7 +627,7 @@ static bool isFPCSafeToPrint(const ConstantFP *CFP) {
       ((StrVal[0] == '-' || StrVal[0] == '+') &&
        (StrVal[1] >= '0' && StrVal[1] <= '9')))
     // Reparse stringized version!
-    return atof(StrVal.c_str()) == CFP->getValue();
+    return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
   return false;
 #endif
 }
@@ -863,9 +884,13 @@ void CWriter::printConstant(Constant *CPV) {
       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
           << "*)&FPConstant" << I->second << ')';
     } else {
-      if (IsNAN(FPC->getValue())) {
+      double V = FPC->getType() == Type::FloatTy ? 
+                 FPC->getValueAPF().convertToFloat() : 
+                 FPC->getValueAPF().convertToDouble();
+      if (IsNAN(V)) {
         // The value is NaN
 
+        // FIXME the actual NaN bits should be emitted.
         // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
         // it's 0x7ff4.
         const unsigned long QuietNaN = 0x7ff8UL;
@@ -874,7 +899,7 @@ void CWriter::printConstant(Constant *CPV) {
         // We need to grab the first part of the FP #
         char Buffer[100];
 
-        uint64_t ll = DoubleToBits(FPC->getValue());
+        uint64_t ll = DoubleToBits(V);
         sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
 
         std::string Num(&Buffer[0], &Buffer[6]);
@@ -886,9 +911,9 @@ void CWriter::printConstant(Constant *CPV) {
         else
           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
               << Buffer << "\") /*nan*/ ";
-      } else if (IsInf(FPC->getValue())) {
+      } else if (IsInf(V)) {
         // The value is Inf
-        if (FPC->getValue() < 0) Out << '-';
+        if (V < 0) Out << '-';
         Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
             << " /*inf*/ ";
       } else {
@@ -896,12 +921,12 @@ void CWriter::printConstant(Constant *CPV) {
 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
         // Print out the constant as a floating point number.
         char Buffer[100];
-        sprintf(Buffer, "%a", FPC->getValue());
+        sprintf(Buffer, "%a", V);
         Num = Buffer;
 #else
-        Num = ftostr(FPC->getValue());
+        Num = ftostr(FPC->getValueAPF());
 #endif
-        Out << Num;
+       Out << Num;
       }
     }
     break;
@@ -1080,6 +1105,34 @@ void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
     printConstant(CPV);
 }
 
+std::string CWriter::GetValueName(const Value *Operand) {
+  std::string Name;
+
+  if (!isa<GlobalValue>(Operand) && Operand->getName() != "") {
+    std::string VarName;
+
+    Name = Operand->getName();
+    VarName.reserve(Name.capacity());
+
+    for (std::string::iterator I = Name.begin(), E = Name.end();
+         I != E; ++I) {
+      char ch = *I;
+
+      if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
+            (ch >= '0' && ch <= '9') || ch == '_'))
+        VarName += '_';
+      else
+        VarName += ch;
+    }
+
+    Name = "llvm_cbe_" + VarName;
+  } else {
+    Name = Mang->getValueName(Operand);
+  }
+
+  return Name;
+}
+
 void CWriter::writeOperandInternal(Value *Operand) {
   if (Instruction *I = dyn_cast<Instruction>(Operand))
     if (isInlinableInst(*I) && !isDirectAlloca(I)) {
@@ -1091,11 +1144,11 @@ void CWriter::writeOperandInternal(Value *Operand) {
     }
 
   Constant* CPV = dyn_cast<Constant>(Operand);
-  if (CPV && !isa<GlobalValue>(CPV)) {
+
+  if (CPV && !isa<GlobalValue>(CPV))
     printConstant(CPV);
-  } else {
-    Out << Mang->getValueName(Operand);
-  }
+  else
+    Out << GetValueName(Operand);
 }
 
 void CWriter::writeOperandRaw(Value *Operand) {
@@ -1103,7 +1156,7 @@ void CWriter::writeOperandRaw(Value *Operand) {
   if (CPV && !isa<GlobalValue>(CPV)) {
     printConstant(CPV);
   } else {
-    Out << Mang->getValueName(Operand);
+    Out << GetValueName(Operand);
   }
 }
 
@@ -1247,8 +1300,8 @@ static void generateCompilerSpecificCode(std::ostream& Out) {
   // Alloca is hard to get, and we don't want to include stdlib.h here.
   Out << "/* get a declaration for alloca */\n"
       << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
-      << "extern void *_alloca(unsigned long);\n"
-      << "#define alloca(x) _alloca(x)\n"
+      << "#define  alloca(x) __builtin_alloca((x))\n"
+      << "#define _alloca(x) __builtin_alloca((x))\n"    
       << "#elif defined(__APPLE__)\n"
       << "extern void *__builtin_alloca(unsigned long);\n"
       << "#define alloca(x) __builtin_alloca(x)\n"
@@ -1263,7 +1316,10 @@ static void generateCompilerSpecificCode(std::ostream& Out) {
       << "#define alloca(x) __builtin_alloca(x)\n"
       << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
       << "#define alloca(x) __builtin_alloca(x)\n"
-      << "#elif !defined(_MSC_VER)\n"
+      << "#elif defined(_MSC_VER)\n"
+      << "#define inline _inline\n"
+      << "#define alloca(x) _alloca(x)\n"
+      << "#else\n"
       << "#include <alloca.h>\n"
       << "#endif\n\n";
 
@@ -1351,19 +1407,14 @@ static void generateCompilerSpecificCode(std::ostream& Out) {
       << "#define __ATTRIBUTE_DTOR__\n"
       << "#define LLVM_ASM(X)\n"
       << "#endif\n\n";
+  
+  Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
+      << "#define __builtin_stack_save() 0   /* not implemented */\n"
+      << "#define __builtin_stack_restore(X) /* noop */\n"
+      << "#endif\n\n";
 
   // Output target-specific code that should be inserted into main.
   Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
-  // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
-  Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
-      << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
-      << "defined(__x86_64__)\n"
-      << "#undef CODE_FOR_MAIN\n"
-      << "#define CODE_FOR_MAIN() \\\n"
-      << "  {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
-      << "  F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
-      << "#endif\n#endif\n";
-
 }
 
 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
@@ -1469,22 +1520,23 @@ bool CWriter::doInitialization(Module &M) {
     Out << "\n/* External Global Variable Declarations */\n";
     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
          I != E; ++I) {
-      if (I->hasExternalLinkage()) {
+
+      if (I->hasExternalLinkage() || I->hasExternalWeakLinkage())
         Out << "extern ";
-        printType(Out, I->getType()->getElementType(), false, 
-                  Mang->getValueName(I));
-        Out << ";\n";
-      } else if (I->hasDLLImportLinkage()) {
+      else if (I->hasDLLImportLinkage())
         Out << "__declspec(dllimport) ";
-        printType(Out, I->getType()->getElementType(), false, 
-                  Mang->getValueName(I));
-        Out << ";\n";        
-      } else if (I->hasExternalWeakLinkage()) {
-        Out << "extern ";
-        printType(Out, I->getType()->getElementType(), false,
-                  Mang->getValueName(I));
-        Out << " __EXTERNAL_WEAK__ ;\n";
-      }
+      else
+        continue; // Internal Global
+
+      // Thread Local Storage
+      if (I->isThreadLocal())
+        Out << "__thread ";
+
+      printType(Out, I->getType()->getElementType(), false, GetValueName(I));
+
+      if (I->hasExternalWeakLinkage())
+         Out << " __EXTERNAL_WEAK__";
+      Out << ";\n";
     }
   }
 
@@ -1527,13 +1579,18 @@ bool CWriter::doInitialization(Module &M) {
         // Ignore special globals, such as debug info.
         if (getGlobalVariableClass(I))
           continue;
-        
+
         if (I->hasInternalLinkage())
           Out << "static ";
         else
           Out << "extern ";
+
+        // Thread Local Storage
+        if (I->isThreadLocal())
+          Out << "__thread ";
+
         printType(Out, I->getType()->getElementType(), false, 
-                  Mang->getValueName(I));
+                  GetValueName(I));
 
         if (I->hasLinkOnceLinkage())
           Out << " __attribute__((common))";
@@ -1556,16 +1613,20 @@ bool CWriter::doInitialization(Module &M) {
         // Ignore special globals, such as debug info.
         if (getGlobalVariableClass(I))
           continue;
-        
+
         if (I->hasInternalLinkage())
           Out << "static ";
         else if (I->hasDLLImportLinkage())
           Out << "__declspec(dllimport) ";
         else if (I->hasDLLExportLinkage())
           Out << "__declspec(dllexport) ";
-            
+
+        // Thread Local Storage
+        if (I->isThreadLocal())
+          Out << "__thread ";
+
         printType(Out, I->getType()->getElementType(), false, 
-                  Mang->getValueName(I));
+                  GetValueName(I));
         if (I->hasLinkOnceLinkage())
           Out << " __attribute__((common))";
         else if (I->hasWeakLinkage())
@@ -1650,17 +1711,20 @@ void CWriter::printFloatingPointConstants(Function &F) {
     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
       if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
           !FPConstantMap.count(FPC)) {
-        double Val = FPC->getValue();
-
         FPConstantMap[FPC] = FPCounter;  // Number the FP constants
 
         if (FPC->getType() == Type::DoubleTy) {
+          double Val = FPC->getValueAPF().convertToDouble();
+          uint64_t i = FPC->getValueAPF().convertToAPInt().getZExtValue();
           Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
-              << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
+              << " = 0x" << std::hex << i << std::dec
               << "ULL;    /* " << Val << " */\n";
         } else if (FPC->getType() == Type::FloatTy) {
+          float Val = FPC->getValueAPF().convertToFloat();
+          uint32_t i = (uint32_t)FPC->getValueAPF().convertToAPInt().
+                                    getZExtValue();
           Out << "static const ConstantFloatTy FPConstant" << FPCounter++
-              << " = 0x" << std::hex << FloatToBits(Val) << std::dec
+              << " = 0x" << std::hex << i << std::dec
               << "U;    /* " << Val << " */\n";
         } else
           assert(0 && "Unknown float type!");
@@ -1768,11 +1832,12 @@ void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
   
   // Loop over the arguments, printing them...
   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
+  const ParamAttrsList *Attrs = FT->getParamAttrs();
 
   std::stringstream FunctionInnards;
 
   // Print out the name...
-  FunctionInnards << Mang->getValueName(F) << '(';
+  FunctionInnards << GetValueName(F) << '(';
 
   bool PrintedArg = false;
   if (!F->isDeclaration()) {
@@ -1791,11 +1856,11 @@ void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
       for (; I != E; ++I) {
         if (PrintedArg) FunctionInnards << ", ";
         if (I->hasName() || !Prototype)
-          ArgName = Mang->getValueName(I);
+          ArgName = GetValueName(I);
         else
           ArgName = "";
         printType(FunctionInnards, I->getType(), 
-            /*isSigned=*/FT->paramHasAttr(Idx, FunctionType::SExtAttribute), 
+            /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt), 
             ArgName);
         PrintedArg = true;
         ++Idx;
@@ -1816,7 +1881,7 @@ void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
     for (; I != E; ++I) {
       if (PrintedArg) FunctionInnards << ", ";
       printType(FunctionInnards, *I,
-             /*isSigned=*/FT->paramHasAttr(Idx, FunctionType::SExtAttribute));
+             /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt));
       PrintedArg = true;
       ++Idx;
     }
@@ -1844,7 +1909,7 @@ void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
     
   // Print out the return type and the signature built above.
   printType(Out, RetTy, 
-            /*isSigned=*/FT->paramHasAttr(0, FunctionType::SExtAttribute), 
+            /*isSigned=*/ Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt), 
             FunctionInnards.str());
 }
 
@@ -1874,7 +1939,7 @@ void CWriter::printFunction(Function &F) {
 
     Out << "  ";
     printType(Out, F.arg_begin()->getType(), false, 
-              Mang->getValueName(F.arg_begin()));
+              GetValueName(F.arg_begin()));
     Out << " = &StructReturn;\n";
   }
 
@@ -1884,18 +1949,18 @@ void CWriter::printFunction(Function &F) {
   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
     if (const AllocaInst *AI = isDirectAlloca(&*I)) {
       Out << "  ";
-      printType(Out, AI->getAllocatedType(), false, Mang->getValueName(AI));
+      printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
       Out << ";    /* Address-exposed local */\n";
       PrintedVar = true;
     } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
       Out << "  ";
-      printType(Out, I->getType(), false, Mang->getValueName(&*I));
+      printType(Out, I->getType(), false, GetValueName(&*I));
       Out << ";\n";
 
       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
         Out << "  ";
         printType(Out, I->getType(), false,
-                  Mang->getValueName(&*I)+"__PHI_TEMPORARY");
+                  GetValueName(&*I)+"__PHI_TEMPORARY");
         Out << ";\n";
       }
       PrintedVar = true;
@@ -1904,7 +1969,7 @@ void CWriter::printFunction(Function &F) {
     // of a union to do the BitCast. This is separate from the need for a
     // variable to hold the result of the BitCast. 
     if (isFPIntBitCast(*I)) {
-      Out << "  llvmBitCastUnion " << Mang->getValueName(&*I)
+      Out << "  llvmBitCastUnion " << GetValueName(&*I)
           << "__BITCAST_TEMPORARY;\n";
       PrintedVar = true;
     }
@@ -1958,7 +2023,7 @@ void CWriter::printBasicBlock(BasicBlock *BB) {
       break;
     }
 
-  if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
+  if (NeedsLabel) Out << GetValueName(BB) << ":\n";
 
   // Output all of the instructions in the basic block...
   for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
@@ -2054,7 +2119,7 @@ void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
     Value *IV = PN->getIncomingValueForBlock(CurBlock);
     if (!isa<UndefValue>(IV)) {
       Out << std::string(Indent, ' ');
-      Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
+      Out << "  " << GetValueName(I) << "__PHI_TEMPORARY = ";
       writeOperand(IV);
       Out << ";   /* for PHI node */\n";
     }
@@ -2281,10 +2346,10 @@ void CWriter::visitCastInst(CastInst &I) {
   Out << '(';
   if (isFPIntBitCast(I)) {
     // These int<->float and long<->double casts need to be handled specially
-    Out << Mang->getValueName(&I) << "__BITCAST_TEMPORARY." 
+    Out << GetValueName(&I) << "__BITCAST_TEMPORARY." 
         << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
     writeOperand(I.getOperand(0));
-    Out << ", " << Mang->getValueName(&I) << "__BITCAST_TEMPORARY."
+    Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
         << getFloatBitCastField(I.getType());
   } else {
     printCast(I.getOpcode(), SrcTy, DstTy);
@@ -2317,7 +2382,14 @@ void CWriter::visitSelectInst(SelectInst &I) {
 
 
 void CWriter::lowerIntrinsics(Function &F) {
-  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
+  // This is used to keep track of intrinsics that get generated to a lowered
+  // function. We must generate the prototypes before the function body which
+  // will only be expanded on first use (by the loop below).
+  std::vector<Function*> prototypesToGen;
+
+  // Examine all the instructions in this function to find the intrinsics that
+  // need to be lowered.
+  for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
       if (CallInst *CI = dyn_cast<CallInst>(I++))
         if (Function *F = CI->getCalledFunction())
@@ -2357,10 +2429,30 @@ void CWriter::lowerIntrinsics(Function &F) {
             } else {
               I = BB->begin();
             }
+            // If the intrinsic got lowered to another call, and that call has
+            // a definition then we need to make sure its prototype is emitted
+            // before any calls to it.
+            if (CallInst *Call = dyn_cast<CallInst>(I))
+              if (Function *NewF = Call->getCalledFunction())
+                if (!NewF->isDeclaration())
+                  prototypesToGen.push_back(NewF);
+
             break;
           }
-}
 
+  // We may have collected some prototypes to emit in the loop above. 
+  // Emit them now, before the function that uses them is emitted. But,
+  // be careful not to emit them twice.
+  std::vector<Function*>::iterator I = prototypesToGen.begin();
+  std::vector<Function*>::iterator E = prototypesToGen.end();
+  for ( ; I != E; ++I) {
+    if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
+      Out << '\n';
+      printFunctionSignature(*I, true);
+      Out << ";\n";
+    }
+  }
+}
 
 
 void CWriter::visitCallInst(CallInst &I) {
@@ -2540,6 +2632,7 @@ void CWriter::visitCallInst(CallInst &I) {
     ++ArgNo;
   }
       
+  const ParamAttrsList *Attrs = FTy->getParamAttrs();
   bool PrintedArg = false;
   unsigned Idx = 1;
   for (; AI != AE; ++AI, ++ArgNo, ++Idx) {
@@ -2548,7 +2641,7 @@ void CWriter::visitCallInst(CallInst &I) {
         (*AI)->getType() != FTy->getParamType(ArgNo)) {
       Out << '(';
       printType(Out, FTy->getParamType(ArgNo), 
-            /*isSigned=*/FTy->paramHasAttr(Idx, FunctionType::SExtAttribute));
+            /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt));
       Out << ')';
     }
     writeOperand(*AI);
@@ -2785,7 +2878,21 @@ void CWriter::visitStoreInst(StoreInst &I) {
   writeOperand(I.getPointerOperand());
   if (I.isVolatile()) Out << ')';
   Out << " = ";
-  writeOperand(I.getOperand(0));
+  Value *Operand = I.getOperand(0);
+  Constant *BitMask = 0;
+  if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
+    if (!ITy->isPowerOf2ByteWidth())
+      // We have a bit width that doesn't match an even power-of-2 byte
+      // size. Consequently we must & the value with the type's bit mask
+      BitMask = ConstantInt::get(ITy, ITy->getBitMask());
+  if (BitMask)
+    Out << "((";
+  writeOperand(Operand);
+  if (BitMask) {
+    Out << ") & ";
+    printConstant(BitMask);
+    Out << ")"; 
+  }
 }
 
 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {