LLVM API Documentation

IntrinsicLowering.cpp

Go to the documentation of this file.
00001 //===-- IntrinsicLowering.cpp - Intrinsic Lowering default implementation -===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the IntrinsicLowering class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Constants.h"
00015 #include "llvm/DerivedTypes.h"
00016 #include "llvm/Module.h"
00017 #include "llvm/Instructions.h"
00018 #include "llvm/Type.h"
00019 #include "llvm/CodeGen/IntrinsicLowering.h"
00020 #include "llvm/Support/Streams.h"
00021 #include "llvm/Target/TargetData.h"
00022 #include "llvm/ADT/SmallVector.h"
00023 #include "llvm/ADT/STLExtras.h"
00024 using namespace llvm;
00025 
00026 template <class ArgIt>
00027 static void EnsureFunctionExists(Module &M, const char *Name,
00028                                  ArgIt ArgBegin, ArgIt ArgEnd,
00029                                  const Type *RetTy) {
00030   // Insert a correctly-typed definition now.
00031   std::vector<const Type *> ParamTys;
00032   for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
00033     ParamTys.push_back(I->getType());
00034   M.getOrInsertFunction(Name, FunctionType::get(RetTy, ParamTys, false));
00035 }
00036 
00037 static void EnsureFPIntrinsicsExist(Module &M, Module::iterator I,
00038                                  const char *FName,
00039                                  const char *DName, const char *LDName) {
00040   // Insert definitions for all the floating point types.
00041   switch((int)I->arg_begin()->getType()->getTypeID()) {
00042   case Type::FloatTyID:
00043     EnsureFunctionExists(M, FName, I->arg_begin(), I->arg_end(),
00044                          Type::FloatTy);
00045   case Type::DoubleTyID:
00046     EnsureFunctionExists(M, DName, I->arg_begin(), I->arg_end(),
00047                          Type::DoubleTy);
00048   case Type::X86_FP80TyID:
00049   case Type::FP128TyID:
00050   case Type::PPC_FP128TyID:
00051     EnsureFunctionExists(M, LDName, I->arg_begin(), I->arg_end(),
00052                          I->arg_begin()->getType());
00053   }
00054 }
00055 
00056 /// ReplaceCallWith - This function is used when we want to lower an intrinsic
00057 /// call to a call of an external function.  This handles hard cases such as
00058 /// when there was already a prototype for the external function, and if that
00059 /// prototype doesn't match the arguments we expect to pass in.
00060 template <class ArgIt>
00061 static CallInst *ReplaceCallWith(const char *NewFn, CallInst *CI,
00062                                  ArgIt ArgBegin, ArgIt ArgEnd,
00063                                  const Type *RetTy, Constant *&FCache) {
00064   if (!FCache) {
00065     // If we haven't already looked up this function, check to see if the
00066     // program already contains a function with this name.
00067     Module *M = CI->getParent()->getParent()->getParent();
00068     // Get or insert the definition now.
00069     std::vector<const Type *> ParamTys;
00070     for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
00071       ParamTys.push_back((*I)->getType());
00072     FCache = M->getOrInsertFunction(NewFn,
00073                                     FunctionType::get(RetTy, ParamTys, false));
00074   }
00075 
00076   SmallVector<Value *, 8> Args(ArgBegin, ArgEnd);
00077   CallInst *NewCI = CallInst::Create(FCache, Args.begin(), Args.end(),
00078                                      CI->getName(), CI);
00079   if (!CI->use_empty())
00080     CI->replaceAllUsesWith(NewCI);
00081   return NewCI;
00082 }
00083 
00084 void IntrinsicLowering::AddPrototypes(Module &M) {
00085   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
00086     if (I->isDeclaration() && !I->use_empty())
00087       switch (I->getIntrinsicID()) {
00088       default: break;
00089       case Intrinsic::setjmp:
00090         EnsureFunctionExists(M, "setjmp", I->arg_begin(), I->arg_end(),
00091                              Type::Int32Ty);
00092         break;
00093       case Intrinsic::longjmp:
00094         EnsureFunctionExists(M, "longjmp", I->arg_begin(), I->arg_end(),
00095                              Type::VoidTy);
00096         break;
00097       case Intrinsic::siglongjmp:
00098         EnsureFunctionExists(M, "abort", I->arg_end(), I->arg_end(),
00099                              Type::VoidTy);
00100         break;
00101       case Intrinsic::memcpy:
00102         M.getOrInsertFunction("memcpy", PointerType::getUnqual(Type::Int8Ty),
00103                               PointerType::getUnqual(Type::Int8Ty), 
00104                               PointerType::getUnqual(Type::Int8Ty), 
00105                               TD.getIntPtrType(), (Type *)0);
00106         break;
00107       case Intrinsic::memmove:
00108         M.getOrInsertFunction("memmove", PointerType::getUnqual(Type::Int8Ty),
00109                               PointerType::getUnqual(Type::Int8Ty), 
00110                               PointerType::getUnqual(Type::Int8Ty), 
00111                               TD.getIntPtrType(), (Type *)0);
00112         break;
00113       case Intrinsic::memset:
00114         M.getOrInsertFunction("memset", PointerType::getUnqual(Type::Int8Ty),
00115                               PointerType::getUnqual(Type::Int8Ty), 
00116                               Type::Int32Ty, 
00117                               TD.getIntPtrType(), (Type *)0);
00118         break;
00119       case Intrinsic::sqrt:
00120         EnsureFPIntrinsicsExist(M, I, "sqrtf", "sqrt", "sqrtl");
00121         break;
00122       case Intrinsic::sin:
00123         EnsureFPIntrinsicsExist(M, I, "sinf", "sin", "sinl");
00124         break;
00125       case Intrinsic::cos:
00126         EnsureFPIntrinsicsExist(M, I, "cosf", "cos", "cosl");
00127         break;
00128       case Intrinsic::pow:
00129         EnsureFPIntrinsicsExist(M, I, "powf", "pow", "powl");
00130         break;
00131       case Intrinsic::log:
00132         EnsureFPIntrinsicsExist(M, I, "logf", "log", "logl");
00133         break;
00134       case Intrinsic::log2:
00135         EnsureFPIntrinsicsExist(M, I, "log2f", "log2", "log2l");
00136         break;
00137       case Intrinsic::log10:
00138         EnsureFPIntrinsicsExist(M, I, "log10f", "log10", "log10l");
00139         break;
00140       case Intrinsic::exp:
00141         EnsureFPIntrinsicsExist(M, I, "expf", "exp", "expl");
00142         break;
00143       case Intrinsic::exp2:
00144         EnsureFPIntrinsicsExist(M, I, "exp2f", "exp2", "exp2l");
00145         break;
00146       }
00147 }
00148 
00149 /// LowerBSWAP - Emit the code to lower bswap of V before the specified
00150 /// instruction IP.
00151 static Value *LowerBSWAP(Value *V, Instruction *IP) {
00152   assert(V->getType()->isInteger() && "Can't bswap a non-integer type!");
00153 
00154   unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
00155   
00156   switch(BitSize) {
00157   default: assert(0 && "Unhandled type size of value to byteswap!");
00158   case 16: {
00159     Value *Tmp1 = BinaryOperator::CreateShl(V,
00160                                 ConstantInt::get(V->getType(),8),"bswap.2",IP);
00161     Value *Tmp2 = BinaryOperator::CreateLShr(V,
00162                                 ConstantInt::get(V->getType(),8),"bswap.1",IP);
00163     V = BinaryOperator::CreateOr(Tmp1, Tmp2, "bswap.i16", IP);
00164     break;
00165   }
00166   case 32: {
00167     Value *Tmp4 = BinaryOperator::CreateShl(V,
00168                               ConstantInt::get(V->getType(),24),"bswap.4", IP);
00169     Value *Tmp3 = BinaryOperator::CreateShl(V,
00170                               ConstantInt::get(V->getType(),8),"bswap.3",IP);
00171     Value *Tmp2 = BinaryOperator::CreateLShr(V,
00172                               ConstantInt::get(V->getType(),8),"bswap.2",IP);
00173     Value *Tmp1 = BinaryOperator::CreateLShr(V,
00174                               ConstantInt::get(V->getType(),24),"bswap.1", IP);
00175     Tmp3 = BinaryOperator::CreateAnd(Tmp3, 
00176                                      ConstantInt::get(Type::Int32Ty, 0xFF0000),
00177                                      "bswap.and3", IP);
00178     Tmp2 = BinaryOperator::CreateAnd(Tmp2, 
00179                                      ConstantInt::get(Type::Int32Ty, 0xFF00),
00180                                      "bswap.and2", IP);
00181     Tmp4 = BinaryOperator::CreateOr(Tmp4, Tmp3, "bswap.or1", IP);
00182     Tmp2 = BinaryOperator::CreateOr(Tmp2, Tmp1, "bswap.or2", IP);
00183     V = BinaryOperator::CreateOr(Tmp4, Tmp2, "bswap.i32", IP);
00184     break;
00185   }
00186   case 64: {
00187     Value *Tmp8 = BinaryOperator::CreateShl(V,
00188                               ConstantInt::get(V->getType(),56),"bswap.8", IP);
00189     Value *Tmp7 = BinaryOperator::CreateShl(V,
00190                               ConstantInt::get(V->getType(),40),"bswap.7", IP);
00191     Value *Tmp6 = BinaryOperator::CreateShl(V,
00192                               ConstantInt::get(V->getType(),24),"bswap.6", IP);
00193     Value *Tmp5 = BinaryOperator::CreateShl(V,
00194                               ConstantInt::get(V->getType(),8),"bswap.5", IP);
00195     Value* Tmp4 = BinaryOperator::CreateLShr(V,
00196                               ConstantInt::get(V->getType(),8),"bswap.4", IP);
00197     Value* Tmp3 = BinaryOperator::CreateLShr(V,
00198                               ConstantInt::get(V->getType(),24),"bswap.3", IP);
00199     Value* Tmp2 = BinaryOperator::CreateLShr(V,
00200                               ConstantInt::get(V->getType(),40),"bswap.2", IP);
00201     Value* Tmp1 = BinaryOperator::CreateLShr(V,
00202                               ConstantInt::get(V->getType(),56),"bswap.1", IP);
00203     Tmp7 = BinaryOperator::CreateAnd(Tmp7,
00204                              ConstantInt::get(Type::Int64Ty, 
00205                                0xFF000000000000ULL),
00206                              "bswap.and7", IP);
00207     Tmp6 = BinaryOperator::CreateAnd(Tmp6,
00208                              ConstantInt::get(Type::Int64Ty, 0xFF0000000000ULL),
00209                              "bswap.and6", IP);
00210     Tmp5 = BinaryOperator::CreateAnd(Tmp5,
00211                              ConstantInt::get(Type::Int64Ty, 0xFF00000000ULL),
00212                              "bswap.and5", IP);
00213     Tmp4 = BinaryOperator::CreateAnd(Tmp4,
00214                              ConstantInt::get(Type::Int64Ty, 0xFF000000ULL),
00215                              "bswap.and4", IP);
00216     Tmp3 = BinaryOperator::CreateAnd(Tmp3,
00217                              ConstantInt::get(Type::Int64Ty, 0xFF0000ULL),
00218                              "bswap.and3", IP);
00219     Tmp2 = BinaryOperator::CreateAnd(Tmp2,
00220                              ConstantInt::get(Type::Int64Ty, 0xFF00ULL),
00221                              "bswap.and2", IP);
00222     Tmp8 = BinaryOperator::CreateOr(Tmp8, Tmp7, "bswap.or1", IP);
00223     Tmp6 = BinaryOperator::CreateOr(Tmp6, Tmp5, "bswap.or2", IP);
00224     Tmp4 = BinaryOperator::CreateOr(Tmp4, Tmp3, "bswap.or3", IP);
00225     Tmp2 = BinaryOperator::CreateOr(Tmp2, Tmp1, "bswap.or4", IP);
00226     Tmp8 = BinaryOperator::CreateOr(Tmp8, Tmp6, "bswap.or5", IP);
00227     Tmp4 = BinaryOperator::CreateOr(Tmp4, Tmp2, "bswap.or6", IP);
00228     V = BinaryOperator::CreateOr(Tmp8, Tmp4, "bswap.i64", IP);
00229     break;
00230   }
00231   }
00232   return V;
00233 }
00234 
00235 /// LowerCTPOP - Emit the code to lower ctpop of V before the specified
00236 /// instruction IP.
00237 static Value *LowerCTPOP(Value *V, Instruction *IP) {
00238   assert(V->getType()->isInteger() && "Can't ctpop a non-integer type!");
00239 
00240   static const uint64_t MaskValues[6] = {
00241     0x5555555555555555ULL, 0x3333333333333333ULL,
00242     0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
00243     0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
00244   };
00245 
00246   unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
00247   unsigned WordSize = (BitSize + 63) / 64;
00248   Value *Count = ConstantInt::get(V->getType(), 0);
00249 
00250   for (unsigned n = 0; n < WordSize; ++n) {
00251     Value *PartValue = V;
00252     for (unsigned i = 1, ct = 0; i < (BitSize>64 ? 64 : BitSize); 
00253          i <<= 1, ++ct) {
00254       Value *MaskCst = ConstantInt::get(V->getType(), MaskValues[ct]);
00255       Value *LHS = BinaryOperator::CreateAnd(
00256                      PartValue, MaskCst, "cppop.and1", IP);
00257       Value *VShift = BinaryOperator::CreateLShr(PartValue,
00258                         ConstantInt::get(V->getType(), i), "ctpop.sh", IP);
00259       Value *RHS = BinaryOperator::CreateAnd(VShift, MaskCst, "cppop.and2", IP);
00260       PartValue = BinaryOperator::CreateAdd(LHS, RHS, "ctpop.step", IP);
00261     }
00262     Count = BinaryOperator::CreateAdd(PartValue, Count, "ctpop.part", IP);
00263     if (BitSize > 64) {
00264       V = BinaryOperator::CreateLShr(V, ConstantInt::get(V->getType(), 64), 
00265                                      "ctpop.part.sh", IP);
00266       BitSize -= 64;
00267     }
00268   }
00269 
00270   return Count;
00271 }
00272 
00273 /// LowerCTLZ - Emit the code to lower ctlz of V before the specified
00274 /// instruction IP.
00275 static Value *LowerCTLZ(Value *V, Instruction *IP) {
00276 
00277   unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
00278   for (unsigned i = 1; i < BitSize; i <<= 1) {
00279     Value *ShVal = ConstantInt::get(V->getType(), i);
00280     ShVal = BinaryOperator::CreateLShr(V, ShVal, "ctlz.sh", IP);
00281     V = BinaryOperator::CreateOr(V, ShVal, "ctlz.step", IP);
00282   }
00283 
00284   V = BinaryOperator::CreateNot(V, "", IP);
00285   return LowerCTPOP(V, IP);
00286 }
00287 
00288 /// Convert the llvm.part.select.iX.iY intrinsic. This intrinsic takes 
00289 /// three integer arguments. The first argument is the Value from which the
00290 /// bits will be selected. It may be of any bit width. The second and third
00291 /// arguments specify a range of bits to select with the second argument 
00292 /// specifying the low bit and the third argument specifying the high bit. Both
00293 /// must be type i32. The result is the corresponding selected bits from the
00294 /// Value in the same width as the Value (first argument). If the low bit index
00295 /// is higher than the high bit index then the inverse selection is done and 
00296 /// the bits are returned in inverse order. 
00297 /// @brief Lowering of llvm.part.select intrinsic.
00298 static Instruction *LowerPartSelect(CallInst *CI) {
00299   // Make sure we're dealing with a part select intrinsic here
00300   Function *F = CI->getCalledFunction();
00301   const FunctionType *FT = F->getFunctionType();
00302   if (!F->isDeclaration() || !FT->getReturnType()->isInteger() ||
00303       FT->getNumParams() != 3 || !FT->getParamType(0)->isInteger() ||
00304       !FT->getParamType(1)->isInteger() || !FT->getParamType(2)->isInteger())
00305     return CI;
00306 
00307   // Get the intrinsic implementation function by converting all the . to _
00308   // in the intrinsic's function name and then reconstructing the function
00309   // declaration.
00310   std::string Name(F->getName());
00311   for (unsigned i = 4; i < Name.length(); ++i)
00312     if (Name[i] == '.')
00313       Name[i] = '_';
00314   Module* M = F->getParent();
00315   F = cast<Function>(M->getOrInsertFunction(Name, FT));
00316   F->setLinkage(GlobalValue::WeakLinkage);
00317 
00318   // If we haven't defined the impl function yet, do so now
00319   if (F->isDeclaration()) {
00320 
00321     // Get the arguments to the function
00322     Function::arg_iterator args = F->arg_begin();
00323     Value* Val = args++; Val->setName("Val");
00324     Value* Lo = args++; Lo->setName("Lo");
00325     Value* Hi = args++; Hi->setName("High");
00326 
00327     // We want to select a range of bits here such that [Hi, Lo] is shifted
00328     // down to the low bits. However, it is quite possible that Hi is smaller
00329     // than Lo in which case the bits have to be reversed. 
00330     
00331     // Create the blocks we will need for the two cases (forward, reverse)
00332     BasicBlock* CurBB   = BasicBlock::Create("entry", F);
00333     BasicBlock *RevSize = BasicBlock::Create("revsize", CurBB->getParent());
00334     BasicBlock *FwdSize = BasicBlock::Create("fwdsize", CurBB->getParent());
00335     BasicBlock *Compute = BasicBlock::Create("compute", CurBB->getParent());
00336     BasicBlock *Reverse = BasicBlock::Create("reverse", CurBB->getParent());
00337     BasicBlock *RsltBlk = BasicBlock::Create("result",  CurBB->getParent());
00338 
00339     // Cast Hi and Lo to the size of Val so the widths are all the same
00340     if (Hi->getType() != Val->getType())
00341       Hi = CastInst::CreateIntegerCast(Hi, Val->getType(), false, 
00342                                          "tmp", CurBB);
00343     if (Lo->getType() != Val->getType())
00344       Lo = CastInst::CreateIntegerCast(Lo, Val->getType(), false, 
00345                                           "tmp", CurBB);
00346 
00347     // Compute a few things that both cases will need, up front.
00348     Constant* Zero = ConstantInt::get(Val->getType(), 0);
00349     Constant* One = ConstantInt::get(Val->getType(), 1);
00350     Constant* AllOnes = ConstantInt::getAllOnesValue(Val->getType());
00351 
00352     // Compare the Hi and Lo bit positions. This is used to determine 
00353     // which case we have (forward or reverse)
00354     ICmpInst *Cmp = new ICmpInst(ICmpInst::ICMP_ULT, Hi, Lo, "less",CurBB);
00355     BranchInst::Create(RevSize, FwdSize, Cmp, CurBB);
00356 
00357     // First, copmute the number of bits in the forward case.
00358     Instruction* FBitSize = 
00359       BinaryOperator::CreateSub(Hi, Lo,"fbits", FwdSize);
00360     BranchInst::Create(Compute, FwdSize);
00361 
00362     // Second, compute the number of bits in the reverse case.
00363     Instruction* RBitSize = 
00364       BinaryOperator::CreateSub(Lo, Hi, "rbits", RevSize);
00365     BranchInst::Create(Compute, RevSize);
00366 
00367     // Now, compute the bit range. Start by getting the bitsize and the shift
00368     // amount (either Hi or Lo) from PHI nodes. Then we compute a mask for 
00369     // the number of bits we want in the range. We shift the bits down to the 
00370     // least significant bits, apply the mask to zero out unwanted high bits, 
00371     // and we have computed the "forward" result. It may still need to be 
00372     // reversed.
00373 
00374     // Get the BitSize from one of the two subtractions
00375     PHINode *BitSize = PHINode::Create(Val->getType(), "bits", Compute);
00376     BitSize->reserveOperandSpace(2);
00377     BitSize->addIncoming(FBitSize, FwdSize);
00378     BitSize->addIncoming(RBitSize, RevSize);
00379 
00380     // Get the ShiftAmount as the smaller of Hi/Lo
00381     PHINode *ShiftAmt = PHINode::Create(Val->getType(), "shiftamt", Compute);
00382     ShiftAmt->reserveOperandSpace(2);
00383     ShiftAmt->addIncoming(Lo, FwdSize);
00384     ShiftAmt->addIncoming(Hi, RevSize);
00385 
00386     // Increment the bit size
00387     Instruction *BitSizePlusOne = 
00388       BinaryOperator::CreateAdd(BitSize, One, "bits", Compute);
00389 
00390     // Create a Mask to zero out the high order bits.
00391     Instruction* Mask = 
00392       BinaryOperator::CreateShl(AllOnes, BitSizePlusOne, "mask", Compute);
00393     Mask = BinaryOperator::CreateNot(Mask, "mask", Compute);
00394 
00395     // Shift the bits down and apply the mask
00396     Instruction* FRes = 
00397       BinaryOperator::CreateLShr(Val, ShiftAmt, "fres", Compute);
00398     FRes = BinaryOperator::CreateAnd(FRes, Mask, "fres", Compute);
00399     BranchInst::Create(Reverse, RsltBlk, Cmp, Compute);
00400 
00401     // In the Reverse block we have the mask already in FRes but we must reverse
00402     // it by shifting FRes bits right and putting them in RRes by shifting them 
00403     // in from left.
00404 
00405     // First set up our loop counters
00406     PHINode *Count = PHINode::Create(Val->getType(), "count", Reverse);
00407     Count->reserveOperandSpace(2);
00408     Count->addIncoming(BitSizePlusOne, Compute);
00409 
00410     // Next, get the value that we are shifting.
00411     PHINode *BitsToShift = PHINode::Create(Val->getType(), "val", Reverse);
00412     BitsToShift->reserveOperandSpace(2);
00413     BitsToShift->addIncoming(FRes, Compute);
00414 
00415     // Finally, get the result of the last computation
00416     PHINode *RRes = PHINode::Create(Val->getType(), "rres", Reverse);
00417     RRes->reserveOperandSpace(2);
00418     RRes->addIncoming(Zero, Compute);
00419 
00420     // Decrement the counter
00421     Instruction *Decr = BinaryOperator::CreateSub(Count, One, "decr", Reverse);
00422     Count->addIncoming(Decr, Reverse);
00423 
00424     // Compute the Bit that we want to move
00425     Instruction *Bit = 
00426       BinaryOperator::CreateAnd(BitsToShift, One, "bit", Reverse);
00427 
00428     // Compute the new value for next iteration.
00429     Instruction *NewVal = 
00430       BinaryOperator::CreateLShr(BitsToShift, One, "rshift", Reverse);
00431     BitsToShift->addIncoming(NewVal, Reverse);
00432 
00433     // Shift the bit into the low bits of the result.
00434     Instruction *NewRes = 
00435       BinaryOperator::CreateShl(RRes, One, "lshift", Reverse);
00436     NewRes = BinaryOperator::CreateOr(NewRes, Bit, "addbit", Reverse);
00437     RRes->addIncoming(NewRes, Reverse);
00438     
00439     // Terminate loop if we've moved all the bits.
00440     ICmpInst *Cond = 
00441       new ICmpInst(ICmpInst::ICMP_EQ, Decr, Zero, "cond", Reverse);
00442     BranchInst::Create(RsltBlk, Reverse, Cond, Reverse);
00443 
00444     // Finally, in the result block, select one of the two results with a PHI
00445     // node and return the result;
00446     CurBB = RsltBlk;
00447     PHINode *BitSelect = PHINode::Create(Val->getType(), "part_select", CurBB);
00448     BitSelect->reserveOperandSpace(2);
00449     BitSelect->addIncoming(FRes, Compute);
00450     BitSelect->addIncoming(NewRes, Reverse);
00451     ReturnInst::Create(BitSelect, CurBB);
00452   }
00453 
00454   // Return a call to the implementation function
00455   Value *Args[] = {
00456     CI->getOperand(1),
00457     CI->getOperand(2),
00458     CI->getOperand(3)
00459   };
00460   return CallInst::Create(F, Args, array_endof(Args), CI->getName(), CI);
00461 }
00462 
00463 /// Convert the llvm.part.set.iX.iY.iZ intrinsic. This intrinsic takes 
00464 /// four integer arguments (iAny %Value, iAny %Replacement, i32 %Low, i32 %High)
00465 /// The first two arguments can be any bit width. The result is the same width
00466 /// as %Value. The operation replaces bits between %Low and %High with the value
00467 /// in %Replacement. If %Replacement is not the same width, it is truncated or
00468 /// zero extended as appropriate to fit the bits being replaced. If %Low is
00469 /// greater than %High then the inverse set of bits are replaced.
00470 /// @brief Lowering of llvm.bit.part.set intrinsic.
00471 static Instruction *LowerPartSet(CallInst *CI) {
00472   // Make sure we're dealing with a part select intrinsic here
00473   Function *F = CI->getCalledFunction();
00474   const FunctionType *FT = F->getFunctionType();
00475   if (!F->isDeclaration() || !FT->getReturnType()->isInteger() ||
00476       FT->getNumParams() != 4 || !FT->getParamType(0)->isInteger() ||
00477       !FT->getParamType(1)->isInteger() || !FT->getParamType(2)->isInteger() ||
00478       !FT->getParamType(3)->isInteger())
00479     return CI;
00480 
00481   // Get the intrinsic implementation function by converting all the . to _
00482   // in the intrinsic's function name and then reconstructing the function
00483   // declaration.
00484   std::string Name(F->getName());
00485   for (unsigned i = 4; i < Name.length(); ++i)
00486     if (Name[i] == '.')
00487       Name[i] = '_';
00488   Module* M = F->getParent();
00489   F = cast<Function>(M->getOrInsertFunction(Name, FT));
00490   F->setLinkage(GlobalValue::WeakLinkage);
00491 
00492   // If we haven't defined the impl function yet, do so now
00493   if (F->isDeclaration()) {
00494     // Get the arguments for the function.
00495     Function::arg_iterator args = F->arg_begin();
00496     Value* Val = args++; Val->setName("Val");
00497     Value* Rep = args++; Rep->setName("Rep");
00498     Value* Lo  = args++; Lo->setName("Lo");
00499     Value* Hi  = args++; Hi->setName("Hi");
00500 
00501     // Get some types we need
00502     const IntegerType* ValTy = cast<IntegerType>(Val->getType());
00503     const IntegerType* RepTy = cast<IntegerType>(Rep->getType());
00504     uint32_t ValBits = ValTy->getBitWidth();
00505     uint32_t RepBits = RepTy->getBitWidth();
00506 
00507     // Constant Definitions
00508     ConstantInt* RepBitWidth = ConstantInt::get(Type::Int32Ty, RepBits);
00509     ConstantInt* RepMask = ConstantInt::getAllOnesValue(RepTy);
00510     ConstantInt* ValMask = ConstantInt::getAllOnesValue(ValTy);
00511     ConstantInt* One = ConstantInt::get(Type::Int32Ty, 1);
00512     ConstantInt* ValOne = ConstantInt::get(ValTy, 1);
00513     ConstantInt* Zero = ConstantInt::get(Type::Int32Ty, 0);
00514     ConstantInt* ValZero = ConstantInt::get(ValTy, 0);
00515 
00516     // Basic blocks we fill in below.
00517     BasicBlock* entry = BasicBlock::Create("entry", F, 0);
00518     BasicBlock* large = BasicBlock::Create("large", F, 0);
00519     BasicBlock* small = BasicBlock::Create("small", F, 0);
00520     BasicBlock* reverse = BasicBlock::Create("reverse", F, 0);
00521     BasicBlock* result = BasicBlock::Create("result", F, 0);
00522 
00523     // BASIC BLOCK: entry
00524     // First, get the number of bits that we're placing as an i32
00525     ICmpInst* is_forward = 
00526       new ICmpInst(ICmpInst::ICMP_ULT, Lo, Hi, "", entry);
00527     SelectInst* Hi_pn = SelectInst::Create(is_forward, Hi, Lo, "", entry);
00528     SelectInst* Lo_pn = SelectInst::Create(is_forward, Lo, Hi, "", entry);
00529     BinaryOperator* NumBits = BinaryOperator::CreateSub(Hi_pn, Lo_pn, "",entry);
00530     NumBits = BinaryOperator::CreateAdd(NumBits, One, "", entry);
00531     // Now, convert Lo and Hi to ValTy bit width
00532     if (ValBits > 32) {
00533       Lo = new ZExtInst(Lo_pn, ValTy, "", entry);
00534     } else if (ValBits < 32) {
00535       Lo = new TruncInst(Lo_pn, ValTy, "", entry);
00536     } else {
00537       Lo = Lo_pn;
00538     }
00539     // Determine if the replacement bits are larger than the number of bits we
00540     // are replacing and deal with it.
00541     ICmpInst* is_large = 
00542       new ICmpInst(ICmpInst::ICMP_ULT, NumBits, RepBitWidth, "", entry);
00543     BranchInst::Create(large, small, is_large, entry);
00544 
00545     // BASIC BLOCK: large
00546     Instruction* MaskBits = 
00547       BinaryOperator::CreateSub(RepBitWidth, NumBits, "", large);
00548     MaskBits = CastInst::CreateIntegerCast(MaskBits, RepMask->getType(), 
00549                                            false, "", large);
00550     BinaryOperator* Mask1 = 
00551       BinaryOperator::CreateLShr(RepMask, MaskBits, "", large);
00552     BinaryOperator* Rep2 = BinaryOperator::CreateAnd(Mask1, Rep, "", large);
00553     BranchInst::Create(small, large);
00554 
00555     // BASIC BLOCK: small
00556     PHINode* Rep3 = PHINode::Create(RepTy, "", small);
00557     Rep3->reserveOperandSpace(2);
00558     Rep3->addIncoming(Rep2, large);
00559     Rep3->addIncoming(Rep, entry);
00560     Value* Rep4 = Rep3;
00561     if (ValBits > RepBits)
00562       Rep4 = new ZExtInst(Rep3, ValTy, "", small);
00563     else if (ValBits < RepBits)
00564       Rep4 = new TruncInst(Rep3, ValTy, "", small);
00565     BranchInst::Create(result, reverse, is_forward, small);
00566 
00567     // BASIC BLOCK: reverse (reverses the bits of the replacement)
00568     // Set up our loop counter as a PHI so we can decrement on each iteration.
00569     // We will loop for the number of bits in the replacement value.
00570     PHINode *Count = PHINode::Create(Type::Int32Ty, "count", reverse);
00571     Count->reserveOperandSpace(2);
00572     Count->addIncoming(NumBits, small);
00573 
00574     // Get the value that we are shifting bits out of as a PHI because
00575     // we'll change this with each iteration.
00576     PHINode *BitsToShift = PHINode::Create(Val->getType(), "val", reverse);
00577     BitsToShift->reserveOperandSpace(2);
00578     BitsToShift->addIncoming(Rep4, small);
00579 
00580     // Get the result of the last computation or zero on first iteration
00581     PHINode *RRes = PHINode::Create(Val->getType(), "rres", reverse);
00582     RRes->reserveOperandSpace(2);
00583     RRes->addIncoming(ValZero, small);
00584 
00585     // Decrement the loop counter by one
00586     Instruction *Decr = BinaryOperator::CreateSub(Count, One, "", reverse);
00587     Count->addIncoming(Decr, reverse);
00588 
00589     // Get the bit that we want to move into the result
00590     Value *Bit = BinaryOperator::CreateAnd(BitsToShift, ValOne, "", reverse);
00591 
00592     // Compute the new value of the bits to shift for the next iteration.
00593     Value *NewVal = BinaryOperator::CreateLShr(BitsToShift, ValOne,"", reverse);
00594     BitsToShift->addIncoming(NewVal, reverse);
00595 
00596     // Shift the bit we extracted into the low bit of the result.
00597     Instruction *NewRes = BinaryOperator::CreateShl(RRes, ValOne, "", reverse);
00598     NewRes = BinaryOperator::CreateOr(NewRes, Bit, "", reverse);
00599     RRes->addIncoming(NewRes, reverse);
00600     
00601     // Terminate loop if we've moved all the bits.
00602     ICmpInst *Cond = new ICmpInst(ICmpInst::ICMP_EQ, Decr, Zero, "", reverse);
00603     BranchInst::Create(result, reverse, Cond, reverse);
00604 
00605     // BASIC BLOCK: result
00606     PHINode *Rplcmnt = PHINode::Create(Val->getType(), "", result);
00607     Rplcmnt->reserveOperandSpace(2);
00608     Rplcmnt->addIncoming(NewRes, reverse);
00609     Rplcmnt->addIncoming(Rep4, small);
00610     Value* t0   = CastInst::CreateIntegerCast(NumBits,ValTy,false,"",result);
00611     Value* t1   = BinaryOperator::CreateShl(ValMask, Lo, "", result);
00612     Value* t2   = BinaryOperator::CreateNot(t1, "", result);
00613     Value* t3   = BinaryOperator::CreateShl(t1, t0, "", result);
00614     Value* t4   = BinaryOperator::CreateOr(t2, t3, "", result);
00615     Value* t5   = BinaryOperator::CreateAnd(t4, Val, "", result);
00616     Value* t6   = BinaryOperator::CreateShl(Rplcmnt, Lo, "", result);
00617     Value* Rslt = BinaryOperator::CreateOr(t5, t6, "part_set", result);
00618     ReturnInst::Create(Rslt, result);
00619   }
00620 
00621   // Return a call to the implementation function
00622   Value *Args[] = {
00623     CI->getOperand(1),
00624     CI->getOperand(2),
00625     CI->getOperand(3),
00626     CI->getOperand(4)
00627   };
00628   return CallInst::Create(F, Args, array_endof(Args), CI->getName(), CI);
00629 }
00630 
00631 static void ReplaceFPIntrinsicWithCall(CallInst *CI, Constant *FCache,
00632                                        Constant *DCache, Constant *LDCache,
00633                                        const char *Fname, const char *Dname,
00634                                        const char *LDname) {
00635   switch (CI->getOperand(1)->getType()->getTypeID()) {
00636   default: assert(0 && "Invalid type in intrinsic"); abort();
00637   case Type::FloatTyID:
00638     ReplaceCallWith(Fname, CI, CI->op_begin()+1, CI->op_end(),
00639                   Type::FloatTy, FCache);
00640     break;
00641   case Type::DoubleTyID:
00642     ReplaceCallWith(Dname, CI, CI->op_begin()+1, CI->op_end(),
00643                   Type::DoubleTy, DCache);
00644     break;
00645   case Type::X86_FP80TyID:
00646   case Type::FP128TyID:
00647   case Type::PPC_FP128TyID:
00648     ReplaceCallWith(LDname, CI, CI->op_begin()+1, CI->op_end(),
00649                   CI->getOperand(1)->getType(), LDCache);
00650     break;
00651   }
00652 }
00653 
00654 void IntrinsicLowering::LowerIntrinsicCall(CallInst *CI) {
00655   Function *Callee = CI->getCalledFunction();
00656   assert(Callee && "Cannot lower an indirect call!");
00657 
00658   switch (Callee->getIntrinsicID()) {
00659   case Intrinsic::not_intrinsic:
00660     cerr << "Cannot lower a call to a non-intrinsic function '"
00661          << Callee->getName() << "'!\n";
00662     abort();
00663   default:
00664     cerr << "Error: Code generator does not support intrinsic function '"
00665          << Callee->getName() << "'!\n";
00666     abort();
00667 
00668     // The setjmp/longjmp intrinsics should only exist in the code if it was
00669     // never optimized (ie, right out of the CFE), or if it has been hacked on
00670     // by the lowerinvoke pass.  In both cases, the right thing to do is to
00671     // convert the call to an explicit setjmp or longjmp call.
00672   case Intrinsic::setjmp: {
00673     static Constant *SetjmpFCache = 0;
00674     Value *V = ReplaceCallWith("setjmp", CI, CI->op_begin()+1, CI->op_end(),
00675                                Type::Int32Ty, SetjmpFCache);
00676     if (CI->getType() != Type::VoidTy)
00677       CI->replaceAllUsesWith(V);
00678     break;
00679   }
00680   case Intrinsic::sigsetjmp:
00681      if (CI->getType() != Type::VoidTy)
00682        CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
00683      break;
00684 
00685   case Intrinsic::longjmp: {
00686     static Constant *LongjmpFCache = 0;
00687     ReplaceCallWith("longjmp", CI, CI->op_begin()+1, CI->op_end(),
00688                     Type::VoidTy, LongjmpFCache);
00689     break;
00690   }
00691 
00692   case Intrinsic::siglongjmp: {
00693     // Insert the call to abort
00694     static Constant *AbortFCache = 0;
00695     ReplaceCallWith("abort", CI, CI->op_end(), CI->op_end(), 
00696                     Type::VoidTy, AbortFCache);
00697     break;
00698   }
00699   case Intrinsic::ctpop:
00700     CI->replaceAllUsesWith(LowerCTPOP(CI->getOperand(1), CI));
00701     break;
00702 
00703   case Intrinsic::bswap:
00704     CI->replaceAllUsesWith(LowerBSWAP(CI->getOperand(1), CI));
00705     break;
00706     
00707   case Intrinsic::ctlz:
00708     CI->replaceAllUsesWith(LowerCTLZ(CI->getOperand(1), CI));
00709     break;
00710 
00711   case Intrinsic::cttz: {
00712     // cttz(x) -> ctpop(~X & (X-1))
00713     Value *Src = CI->getOperand(1);
00714     Value *NotSrc = BinaryOperator::CreateNot(Src, Src->getName()+".not", CI);
00715     Value *SrcM1 = ConstantInt::get(Src->getType(), 1);
00716     SrcM1 = BinaryOperator::CreateSub(Src, SrcM1, "", CI);
00717     Src = LowerCTPOP(BinaryOperator::CreateAnd(NotSrc, SrcM1, "", CI), CI);
00718     CI->replaceAllUsesWith(Src);
00719     break;
00720   }
00721 
00722   case Intrinsic::part_select:
00723     CI->replaceAllUsesWith(LowerPartSelect(CI));
00724     break;
00725 
00726   case Intrinsic::part_set:
00727     CI->replaceAllUsesWith(LowerPartSet(CI));
00728     break;
00729 
00730   case Intrinsic::stacksave:
00731   case Intrinsic::stackrestore: {
00732     static bool Warned = false;
00733     if (!Warned)
00734       cerr << "WARNING: this target does not support the llvm.stack"
00735            << (Callee->getIntrinsicID() == Intrinsic::stacksave ?
00736                "save" : "restore") << " intrinsic.\n";
00737     Warned = true;
00738     if (Callee->getIntrinsicID() == Intrinsic::stacksave)
00739       CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
00740     break;
00741   }
00742     
00743   case Intrinsic::returnaddress:
00744   case Intrinsic::frameaddress:
00745     cerr << "WARNING: this target does not support the llvm."
00746          << (Callee->getIntrinsicID() == Intrinsic::returnaddress ?
00747              "return" : "frame") << "address intrinsic.\n";
00748     CI->replaceAllUsesWith(ConstantPointerNull::get(
00749                                             cast<PointerType>(CI->getType())));
00750     break;
00751 
00752   case Intrinsic::prefetch:
00753     break;    // Simply strip out prefetches on unsupported architectures
00754 
00755   case Intrinsic::pcmarker:
00756     break;    // Simply strip out pcmarker on unsupported architectures
00757   case Intrinsic::readcyclecounter: {
00758     cerr << "WARNING: this target does not support the llvm.readcyclecoun"
00759          << "ter intrinsic.  It is being lowered to a constant 0\n";
00760     CI->replaceAllUsesWith(ConstantInt::get(Type::Int64Ty, 0));
00761     break;
00762   }
00763 
00764   case Intrinsic::dbg_stoppoint:
00765   case Intrinsic::dbg_region_start:
00766   case Intrinsic::dbg_region_end:
00767   case Intrinsic::dbg_func_start:
00768   case Intrinsic::dbg_declare:
00769     break;    // Simply strip out debugging intrinsics
00770 
00771   case Intrinsic::eh_exception:
00772   case Intrinsic::eh_selector_i32:
00773   case Intrinsic::eh_selector_i64:
00774     CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
00775     break;
00776 
00777   case Intrinsic::eh_typeid_for_i32:
00778   case Intrinsic::eh_typeid_for_i64:
00779     // Return something different to eh_selector.
00780     CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
00781     break;
00782 
00783   case Intrinsic::var_annotation:
00784     break;   // Strip out annotate intrinsic
00785     
00786   case Intrinsic::memcpy: {
00787     static Constant *MemcpyFCache = 0;
00788     Value *Size = CI->getOperand(3);
00789     const Type *IntPtr = TD.getIntPtrType();
00790     if (Size->getType()->getPrimitiveSizeInBits() <
00791         IntPtr->getPrimitiveSizeInBits())
00792       Size = new ZExtInst(Size, IntPtr, "", CI);
00793     else if (Size->getType()->getPrimitiveSizeInBits() >
00794              IntPtr->getPrimitiveSizeInBits())
00795       Size = new TruncInst(Size, IntPtr, "", CI);
00796     Value *Ops[3];
00797     Ops[0] = CI->getOperand(1);
00798     Ops[1] = CI->getOperand(2);
00799     Ops[2] = Size;
00800     ReplaceCallWith("memcpy", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
00801                     MemcpyFCache);
00802     break;
00803   }
00804   case Intrinsic::memmove: {
00805     static Constant *MemmoveFCache = 0;
00806     Value *Size = CI->getOperand(3);
00807     const Type *IntPtr = TD.getIntPtrType();
00808     if (Size->getType()->getPrimitiveSizeInBits() <
00809         IntPtr->getPrimitiveSizeInBits())
00810       Size = new ZExtInst(Size, IntPtr, "", CI);
00811     else if (Size->getType()->getPrimitiveSizeInBits() >
00812              IntPtr->getPrimitiveSizeInBits())
00813       Size = new TruncInst(Size, IntPtr, "", CI);
00814     Value *Ops[3];
00815     Ops[0] = CI->getOperand(1);
00816     Ops[1] = CI->getOperand(2);
00817     Ops[2] = Size;
00818     ReplaceCallWith("memmove", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
00819                     MemmoveFCache);
00820     break;
00821   }
00822   case Intrinsic::memset: {
00823     static Constant *MemsetFCache = 0;
00824     Value *Size = CI->getOperand(3);
00825     const Type *IntPtr = TD.getIntPtrType();
00826     if (Size->getType()->getPrimitiveSizeInBits() <
00827         IntPtr->getPrimitiveSizeInBits())
00828       Size = new ZExtInst(Size, IntPtr, "", CI);
00829     else if (Size->getType()->getPrimitiveSizeInBits() >
00830              IntPtr->getPrimitiveSizeInBits())
00831       Size = new TruncInst(Size, IntPtr, "", CI);
00832     Value *Ops[3];
00833     Ops[0] = CI->getOperand(1);
00834     // Extend the amount to i32.
00835     Ops[1] = new ZExtInst(CI->getOperand(2), Type::Int32Ty, "", CI);
00836     Ops[2] = Size;
00837     ReplaceCallWith("memset", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
00838                     MemsetFCache);
00839     break;
00840   }
00841   case Intrinsic::sqrt: {
00842     static Constant *sqrtFCache = 0;
00843     static Constant *sqrtDCache = 0;
00844     static Constant *sqrtLDCache = 0;
00845     ReplaceFPIntrinsicWithCall(CI, sqrtFCache, sqrtDCache, sqrtLDCache,
00846                                "sqrtf", "sqrt", "sqrtl");
00847     break;
00848   }
00849   case Intrinsic::log: {
00850     static Constant *logFCache = 0;
00851     static Constant *logDCache = 0;
00852     static Constant *logLDCache = 0;
00853     ReplaceFPIntrinsicWithCall(CI, logFCache, logDCache, logLDCache,
00854                                "logf", "log", "logl");
00855     break;
00856   }
00857   case Intrinsic::log2: {
00858     static Constant *log2FCache = 0;
00859     static Constant *log2DCache = 0;
00860     static Constant *log2LDCache = 0;
00861     ReplaceFPIntrinsicWithCall(CI, log2FCache, log2DCache, log2LDCache,
00862                                "log2f", "log2", "log2l");
00863     break;
00864   }
00865   case Intrinsic::log10: {
00866     static Constant *log10FCache = 0;
00867     static Constant *log10DCache = 0;
00868     static Constant *log10LDCache = 0;
00869     ReplaceFPIntrinsicWithCall(CI, log10FCache, log10DCache, log10LDCache,
00870                                "log10f", "log10", "log10l");
00871     break;
00872   }
00873   case Intrinsic::exp: {
00874     static Constant *expFCache = 0;
00875     static Constant *expDCache = 0;
00876     static Constant *expLDCache = 0;
00877     ReplaceFPIntrinsicWithCall(CI, expFCache, expDCache, expLDCache,
00878                                "expf", "exp", "expl");
00879     break;
00880   }
00881   case Intrinsic::exp2: {
00882     static Constant *exp2FCache = 0;
00883     static Constant *exp2DCache = 0;
00884     static Constant *exp2LDCache = 0;
00885     ReplaceFPIntrinsicWithCall(CI, exp2FCache, exp2DCache, exp2LDCache,
00886                                "exp2f", "exp2", "exp2l");
00887     break;
00888   }
00889   case Intrinsic::pow: {
00890     static Constant *powFCache = 0;
00891     static Constant *powDCache = 0;
00892     static Constant *powLDCache = 0;
00893     ReplaceFPIntrinsicWithCall(CI, powFCache, powDCache, powLDCache,
00894                                "powf", "pow", "powl");
00895     break;
00896   }
00897   case Intrinsic::flt_rounds:
00898      // Lower to "round to the nearest"
00899      if (CI->getType() != Type::VoidTy)
00900        CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
00901      break;
00902   }
00903 
00904   assert(CI->use_empty() &&
00905          "Lowering should have eliminated any uses of the intrinsic call!");
00906   CI->eraseFromParent();
00907 }