IntrinsicLowering.cpp revision c0425b646f726de9b2422bc48ec316c4be9f6d7f
1//===-- IntrinsicLowering.cpp - Intrinsic Lowering default implementation -===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the IntrinsicLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Constants.h"
15#include "llvm/DerivedTypes.h"
16#include "llvm/Module.h"
17#include "llvm/Instructions.h"
18#include "llvm/Type.h"
19#include "llvm/CodeGen/IntrinsicLowering.h"
20#include "llvm/Support/Streams.h"
21#include "llvm/Target/TargetData.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/STLExtras.h"
24using namespace llvm;
25
26template <class ArgIt>
27static void EnsureFunctionExists(Module &M, const char *Name,
28                                 ArgIt ArgBegin, ArgIt ArgEnd,
29                                 const Type *RetTy) {
30  // Insert a correctly-typed definition now.
31  std::vector<const Type *> ParamTys;
32  for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
33    ParamTys.push_back(I->getType());
34  M.getOrInsertFunction(Name, FunctionType::get(RetTy, ParamTys, false));
35}
36
37static void EnsureFPIntrinsicsExist(Module &M, Module::iterator I,
38                                 const char *FName,
39                                 const char *DName, const char *LDName) {
40  // Insert definitions for all the floating point types.
41  switch((int)I->arg_begin()->getType()->getTypeID()) {
42  case Type::FloatTyID:
43    EnsureFunctionExists(M, FName, I->arg_begin(), I->arg_end(),
44                         Type::FloatTy);
45  case Type::DoubleTyID:
46    EnsureFunctionExists(M, DName, I->arg_begin(), I->arg_end(),
47                         Type::DoubleTy);
48  case Type::X86_FP80TyID:
49  case Type::FP128TyID:
50  case Type::PPC_FP128TyID:
51    EnsureFunctionExists(M, LDName, I->arg_begin(), I->arg_end(),
52                         I->arg_begin()->getType());
53  }
54}
55
56/// ReplaceCallWith - This function is used when we want to lower an intrinsic
57/// call to a call of an external function.  This handles hard cases such as
58/// when there was already a prototype for the external function, and if that
59/// prototype doesn't match the arguments we expect to pass in.
60template <class ArgIt>
61static CallInst *ReplaceCallWith(const char *NewFn, CallInst *CI,
62                                 ArgIt ArgBegin, ArgIt ArgEnd,
63                                 const Type *RetTy, Constant *&FCache) {
64  if (!FCache) {
65    // If we haven't already looked up this function, check to see if the
66    // program already contains a function with this name.
67    Module *M = CI->getParent()->getParent()->getParent();
68    // Get or insert the definition now.
69    std::vector<const Type *> ParamTys;
70    for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
71      ParamTys.push_back((*I)->getType());
72    FCache = M->getOrInsertFunction(NewFn,
73                                    FunctionType::get(RetTy, ParamTys, false));
74  }
75
76  SmallVector<Value *, 8> Args(ArgBegin, ArgEnd);
77  CallInst *NewCI = CallInst::Create(FCache, Args.begin(), Args.end(),
78                                     CI->getName(), CI);
79  if (!CI->use_empty())
80    CI->replaceAllUsesWith(NewCI);
81  return NewCI;
82}
83
84void IntrinsicLowering::AddPrototypes(Module &M) {
85  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
86    if (I->isDeclaration() && !I->use_empty())
87      switch (I->getIntrinsicID()) {
88      default: break;
89      case Intrinsic::setjmp:
90        EnsureFunctionExists(M, "setjmp", I->arg_begin(), I->arg_end(),
91                             Type::Int32Ty);
92        break;
93      case Intrinsic::longjmp:
94        EnsureFunctionExists(M, "longjmp", I->arg_begin(), I->arg_end(),
95                             Type::VoidTy);
96        break;
97      case Intrinsic::siglongjmp:
98        EnsureFunctionExists(M, "abort", I->arg_end(), I->arg_end(),
99                             Type::VoidTy);
100        break;
101      case Intrinsic::memcpy:
102        M.getOrInsertFunction("memcpy", PointerType::getUnqual(Type::Int8Ty),
103                              PointerType::getUnqual(Type::Int8Ty),
104                              PointerType::getUnqual(Type::Int8Ty),
105                              TD.getIntPtrType(), (Type *)0);
106        break;
107      case Intrinsic::memmove:
108        M.getOrInsertFunction("memmove", PointerType::getUnqual(Type::Int8Ty),
109                              PointerType::getUnqual(Type::Int8Ty),
110                              PointerType::getUnqual(Type::Int8Ty),
111                              TD.getIntPtrType(), (Type *)0);
112        break;
113      case Intrinsic::memset:
114        M.getOrInsertFunction("memset", PointerType::getUnqual(Type::Int8Ty),
115                              PointerType::getUnqual(Type::Int8Ty),
116                              Type::Int32Ty,
117                              TD.getIntPtrType(), (Type *)0);
118        break;
119      case Intrinsic::sqrt:
120        EnsureFPIntrinsicsExist(M, I, "sqrtf", "sqrt", "sqrtl");
121        break;
122      case Intrinsic::sin:
123        EnsureFPIntrinsicsExist(M, I, "sinf", "sin", "sinl");
124        break;
125      case Intrinsic::cos:
126        EnsureFPIntrinsicsExist(M, I, "cosf", "cos", "cosl");
127        break;
128      case Intrinsic::pow:
129        EnsureFPIntrinsicsExist(M, I, "powf", "pow", "powl");
130        break;
131      case Intrinsic::log:
132        EnsureFPIntrinsicsExist(M, I, "logf", "log", "logl");
133        break;
134      case Intrinsic::log2:
135        EnsureFPIntrinsicsExist(M, I, "log2f", "log2", "log2l");
136        break;
137      case Intrinsic::log10:
138        EnsureFPIntrinsicsExist(M, I, "log10f", "log10", "log10l");
139        break;
140      case Intrinsic::exp:
141        EnsureFPIntrinsicsExist(M, I, "expf", "exp", "expl");
142        break;
143      case Intrinsic::exp2:
144        EnsureFPIntrinsicsExist(M, I, "exp2f", "exp2", "exp2l");
145        break;
146      }
147}
148
149/// LowerBSWAP - Emit the code to lower bswap of V before the specified
150/// instruction IP.
151static Value *LowerBSWAP(Value *V, Instruction *IP) {
152  assert(V->getType()->isInteger() && "Can't bswap a non-integer type!");
153
154  unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
155
156  switch(BitSize) {
157  default: assert(0 && "Unhandled type size of value to byteswap!");
158  case 16: {
159    Value *Tmp1 = BinaryOperator::CreateShl(V,
160                                ConstantInt::get(V->getType(),8),"bswap.2",IP);
161    Value *Tmp2 = BinaryOperator::CreateLShr(V,
162                                ConstantInt::get(V->getType(),8),"bswap.1",IP);
163    V = BinaryOperator::CreateOr(Tmp1, Tmp2, "bswap.i16", IP);
164    break;
165  }
166  case 32: {
167    Value *Tmp4 = BinaryOperator::CreateShl(V,
168                              ConstantInt::get(V->getType(),24),"bswap.4", IP);
169    Value *Tmp3 = BinaryOperator::CreateShl(V,
170                              ConstantInt::get(V->getType(),8),"bswap.3",IP);
171    Value *Tmp2 = BinaryOperator::CreateLShr(V,
172                              ConstantInt::get(V->getType(),8),"bswap.2",IP);
173    Value *Tmp1 = BinaryOperator::CreateLShr(V,
174                              ConstantInt::get(V->getType(),24),"bswap.1", IP);
175    Tmp3 = BinaryOperator::CreateAnd(Tmp3,
176                                     ConstantInt::get(Type::Int32Ty, 0xFF0000),
177                                     "bswap.and3", IP);
178    Tmp2 = BinaryOperator::CreateAnd(Tmp2,
179                                     ConstantInt::get(Type::Int32Ty, 0xFF00),
180                                     "bswap.and2", IP);
181    Tmp4 = BinaryOperator::CreateOr(Tmp4, Tmp3, "bswap.or1", IP);
182    Tmp2 = BinaryOperator::CreateOr(Tmp2, Tmp1, "bswap.or2", IP);
183    V = BinaryOperator::CreateOr(Tmp4, Tmp2, "bswap.i32", IP);
184    break;
185  }
186  case 64: {
187    Value *Tmp8 = BinaryOperator::CreateShl(V,
188                              ConstantInt::get(V->getType(),56),"bswap.8", IP);
189    Value *Tmp7 = BinaryOperator::CreateShl(V,
190                              ConstantInt::get(V->getType(),40),"bswap.7", IP);
191    Value *Tmp6 = BinaryOperator::CreateShl(V,
192                              ConstantInt::get(V->getType(),24),"bswap.6", IP);
193    Value *Tmp5 = BinaryOperator::CreateShl(V,
194                              ConstantInt::get(V->getType(),8),"bswap.5", IP);
195    Value* Tmp4 = BinaryOperator::CreateLShr(V,
196                              ConstantInt::get(V->getType(),8),"bswap.4", IP);
197    Value* Tmp3 = BinaryOperator::CreateLShr(V,
198                              ConstantInt::get(V->getType(),24),"bswap.3", IP);
199    Value* Tmp2 = BinaryOperator::CreateLShr(V,
200                              ConstantInt::get(V->getType(),40),"bswap.2", IP);
201    Value* Tmp1 = BinaryOperator::CreateLShr(V,
202                              ConstantInt::get(V->getType(),56),"bswap.1", IP);
203    Tmp7 = BinaryOperator::CreateAnd(Tmp7,
204                             ConstantInt::get(Type::Int64Ty,
205                               0xFF000000000000ULL),
206                             "bswap.and7", IP);
207    Tmp6 = BinaryOperator::CreateAnd(Tmp6,
208                             ConstantInt::get(Type::Int64Ty, 0xFF0000000000ULL),
209                             "bswap.and6", IP);
210    Tmp5 = BinaryOperator::CreateAnd(Tmp5,
211                             ConstantInt::get(Type::Int64Ty, 0xFF00000000ULL),
212                             "bswap.and5", IP);
213    Tmp4 = BinaryOperator::CreateAnd(Tmp4,
214                             ConstantInt::get(Type::Int64Ty, 0xFF000000ULL),
215                             "bswap.and4", IP);
216    Tmp3 = BinaryOperator::CreateAnd(Tmp3,
217                             ConstantInt::get(Type::Int64Ty, 0xFF0000ULL),
218                             "bswap.and3", IP);
219    Tmp2 = BinaryOperator::CreateAnd(Tmp2,
220                             ConstantInt::get(Type::Int64Ty, 0xFF00ULL),
221                             "bswap.and2", IP);
222    Tmp8 = BinaryOperator::CreateOr(Tmp8, Tmp7, "bswap.or1", IP);
223    Tmp6 = BinaryOperator::CreateOr(Tmp6, Tmp5, "bswap.or2", IP);
224    Tmp4 = BinaryOperator::CreateOr(Tmp4, Tmp3, "bswap.or3", IP);
225    Tmp2 = BinaryOperator::CreateOr(Tmp2, Tmp1, "bswap.or4", IP);
226    Tmp8 = BinaryOperator::CreateOr(Tmp8, Tmp6, "bswap.or5", IP);
227    Tmp4 = BinaryOperator::CreateOr(Tmp4, Tmp2, "bswap.or6", IP);
228    V = BinaryOperator::CreateOr(Tmp8, Tmp4, "bswap.i64", IP);
229    break;
230  }
231  }
232  return V;
233}
234
235/// LowerCTPOP - Emit the code to lower ctpop of V before the specified
236/// instruction IP.
237static Value *LowerCTPOP(Value *V, Instruction *IP) {
238  assert(V->getType()->isInteger() && "Can't ctpop a non-integer type!");
239
240  static const uint64_t MaskValues[6] = {
241    0x5555555555555555ULL, 0x3333333333333333ULL,
242    0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
243    0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
244  };
245
246  unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
247  unsigned WordSize = (BitSize + 63) / 64;
248  Value *Count = ConstantInt::get(V->getType(), 0);
249
250  for (unsigned n = 0; n < WordSize; ++n) {
251    Value *PartValue = V;
252    for (unsigned i = 1, ct = 0; i < (BitSize>64 ? 64 : BitSize);
253         i <<= 1, ++ct) {
254      Value *MaskCst = ConstantInt::get(V->getType(), MaskValues[ct]);
255      Value *LHS = BinaryOperator::CreateAnd(
256                     PartValue, MaskCst, "cppop.and1", IP);
257      Value *VShift = BinaryOperator::CreateLShr(PartValue,
258                        ConstantInt::get(V->getType(), i), "ctpop.sh", IP);
259      Value *RHS = BinaryOperator::CreateAnd(VShift, MaskCst, "cppop.and2", IP);
260      PartValue = BinaryOperator::CreateAdd(LHS, RHS, "ctpop.step", IP);
261    }
262    Count = BinaryOperator::CreateAdd(PartValue, Count, "ctpop.part", IP);
263    if (BitSize > 64) {
264      V = BinaryOperator::CreateLShr(V, ConstantInt::get(V->getType(), 64),
265                                     "ctpop.part.sh", IP);
266      BitSize -= 64;
267    }
268  }
269
270  return Count;
271}
272
273/// LowerCTLZ - Emit the code to lower ctlz of V before the specified
274/// instruction IP.
275static Value *LowerCTLZ(Value *V, Instruction *IP) {
276
277  unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
278  for (unsigned i = 1; i < BitSize; i <<= 1) {
279    Value *ShVal = ConstantInt::get(V->getType(), i);
280    ShVal = BinaryOperator::CreateLShr(V, ShVal, "ctlz.sh", IP);
281    V = BinaryOperator::CreateOr(V, ShVal, "ctlz.step", IP);
282  }
283
284  V = BinaryOperator::CreateNot(V, "", IP);
285  return LowerCTPOP(V, IP);
286}
287
288/// Convert the llvm.part.select.iX.iY intrinsic. This intrinsic takes
289/// three integer arguments. The first argument is the Value from which the
290/// bits will be selected. It may be of any bit width. The second and third
291/// arguments specify a range of bits to select with the second argument
292/// specifying the low bit and the third argument specifying the high bit. Both
293/// must be type i32. The result is the corresponding selected bits from the
294/// Value in the same width as the Value (first argument). If the low bit index
295/// is higher than the high bit index then the inverse selection is done and
296/// the bits are returned in inverse order.
297/// @brief Lowering of llvm.part.select intrinsic.
298static Instruction *LowerPartSelect(CallInst *CI) {
299  // Make sure we're dealing with a part select intrinsic here
300  Function *F = CI->getCalledFunction();
301  const FunctionType *FT = F->getFunctionType();
302  if (!F->isDeclaration() || !FT->getReturnType()->isInteger() ||
303      FT->getNumParams() != 3 || !FT->getParamType(0)->isInteger() ||
304      !FT->getParamType(1)->isInteger() || !FT->getParamType(2)->isInteger())
305    return CI;
306
307  // Get the intrinsic implementation function by converting all the . to _
308  // in the intrinsic's function name and then reconstructing the function
309  // declaration.
310  std::string Name(F->getName());
311  for (unsigned i = 4; i < Name.length(); ++i)
312    if (Name[i] == '.')
313      Name[i] = '_';
314  Module* M = F->getParent();
315  F = cast<Function>(M->getOrInsertFunction(Name, FT));
316  F->setLinkage(GlobalValue::WeakLinkage);
317
318  // If we haven't defined the impl function yet, do so now
319  if (F->isDeclaration()) {
320
321    // Get the arguments to the function
322    Function::arg_iterator args = F->arg_begin();
323    Value* Val = args++; Val->setName("Val");
324    Value* Lo = args++; Lo->setName("Lo");
325    Value* Hi = args++; Hi->setName("High");
326
327    // We want to select a range of bits here such that [Hi, Lo] is shifted
328    // down to the low bits. However, it is quite possible that Hi is smaller
329    // than Lo in which case the bits have to be reversed.
330
331    // Create the blocks we will need for the two cases (forward, reverse)
332    BasicBlock* CurBB   = BasicBlock::Create("entry", F);
333    BasicBlock *RevSize = BasicBlock::Create("revsize", CurBB->getParent());
334    BasicBlock *FwdSize = BasicBlock::Create("fwdsize", CurBB->getParent());
335    BasicBlock *Compute = BasicBlock::Create("compute", CurBB->getParent());
336    BasicBlock *Reverse = BasicBlock::Create("reverse", CurBB->getParent());
337    BasicBlock *RsltBlk = BasicBlock::Create("result",  CurBB->getParent());
338
339    // Cast Hi and Lo to the size of Val so the widths are all the same
340    if (Hi->getType() != Val->getType())
341      Hi = CastInst::CreateIntegerCast(Hi, Val->getType(), false,
342                                         "tmp", CurBB);
343    if (Lo->getType() != Val->getType())
344      Lo = CastInst::CreateIntegerCast(Lo, Val->getType(), false,
345                                          "tmp", CurBB);
346
347    // Compute a few things that both cases will need, up front.
348    Constant* Zero = ConstantInt::get(Val->getType(), 0);
349    Constant* One = ConstantInt::get(Val->getType(), 1);
350    Constant* AllOnes = ConstantInt::getAllOnesValue(Val->getType());
351
352    // Compare the Hi and Lo bit positions. This is used to determine
353    // which case we have (forward or reverse)
354    ICmpInst *Cmp = new ICmpInst(ICmpInst::ICMP_ULT, Hi, Lo, "less",CurBB);
355    BranchInst::Create(RevSize, FwdSize, Cmp, CurBB);
356
357    // First, copmute the number of bits in the forward case.
358    Instruction* FBitSize =
359      BinaryOperator::CreateSub(Hi, Lo,"fbits", FwdSize);
360    BranchInst::Create(Compute, FwdSize);
361
362    // Second, compute the number of bits in the reverse case.
363    Instruction* RBitSize =
364      BinaryOperator::CreateSub(Lo, Hi, "rbits", RevSize);
365    BranchInst::Create(Compute, RevSize);
366
367    // Now, compute the bit range. Start by getting the bitsize and the shift
368    // amount (either Hi or Lo) from PHI nodes. Then we compute a mask for
369    // the number of bits we want in the range. We shift the bits down to the
370    // least significant bits, apply the mask to zero out unwanted high bits,
371    // and we have computed the "forward" result. It may still need to be
372    // reversed.
373
374    // Get the BitSize from one of the two subtractions
375    PHINode *BitSize = PHINode::Create(Val->getType(), "bits", Compute);
376    BitSize->reserveOperandSpace(2);
377    BitSize->addIncoming(FBitSize, FwdSize);
378    BitSize->addIncoming(RBitSize, RevSize);
379
380    // Get the ShiftAmount as the smaller of Hi/Lo
381    PHINode *ShiftAmt = PHINode::Create(Val->getType(), "shiftamt", Compute);
382    ShiftAmt->reserveOperandSpace(2);
383    ShiftAmt->addIncoming(Lo, FwdSize);
384    ShiftAmt->addIncoming(Hi, RevSize);
385
386    // Increment the bit size
387    Instruction *BitSizePlusOne =
388      BinaryOperator::CreateAdd(BitSize, One, "bits", Compute);
389
390    // Create a Mask to zero out the high order bits.
391    Instruction* Mask =
392      BinaryOperator::CreateShl(AllOnes, BitSizePlusOne, "mask", Compute);
393    Mask = BinaryOperator::CreateNot(Mask, "mask", Compute);
394
395    // Shift the bits down and apply the mask
396    Instruction* FRes =
397      BinaryOperator::CreateLShr(Val, ShiftAmt, "fres", Compute);
398    FRes = BinaryOperator::CreateAnd(FRes, Mask, "fres", Compute);
399    BranchInst::Create(Reverse, RsltBlk, Cmp, Compute);
400
401    // In the Reverse block we have the mask already in FRes but we must reverse
402    // it by shifting FRes bits right and putting them in RRes by shifting them
403    // in from left.
404
405    // First set up our loop counters
406    PHINode *Count = PHINode::Create(Val->getType(), "count", Reverse);
407    Count->reserveOperandSpace(2);
408    Count->addIncoming(BitSizePlusOne, Compute);
409
410    // Next, get the value that we are shifting.
411    PHINode *BitsToShift = PHINode::Create(Val->getType(), "val", Reverse);
412    BitsToShift->reserveOperandSpace(2);
413    BitsToShift->addIncoming(FRes, Compute);
414
415    // Finally, get the result of the last computation
416    PHINode *RRes = PHINode::Create(Val->getType(), "rres", Reverse);
417    RRes->reserveOperandSpace(2);
418    RRes->addIncoming(Zero, Compute);
419
420    // Decrement the counter
421    Instruction *Decr = BinaryOperator::CreateSub(Count, One, "decr", Reverse);
422    Count->addIncoming(Decr, Reverse);
423
424    // Compute the Bit that we want to move
425    Instruction *Bit =
426      BinaryOperator::CreateAnd(BitsToShift, One, "bit", Reverse);
427
428    // Compute the new value for next iteration.
429    Instruction *NewVal =
430      BinaryOperator::CreateLShr(BitsToShift, One, "rshift", Reverse);
431    BitsToShift->addIncoming(NewVal, Reverse);
432
433    // Shift the bit into the low bits of the result.
434    Instruction *NewRes =
435      BinaryOperator::CreateShl(RRes, One, "lshift", Reverse);
436    NewRes = BinaryOperator::CreateOr(NewRes, Bit, "addbit", Reverse);
437    RRes->addIncoming(NewRes, Reverse);
438
439    // Terminate loop if we've moved all the bits.
440    ICmpInst *Cond =
441      new ICmpInst(ICmpInst::ICMP_EQ, Decr, Zero, "cond", Reverse);
442    BranchInst::Create(RsltBlk, Reverse, Cond, Reverse);
443
444    // Finally, in the result block, select one of the two results with a PHI
445    // node and return the result;
446    CurBB = RsltBlk;
447    PHINode *BitSelect = PHINode::Create(Val->getType(), "part_select", CurBB);
448    BitSelect->reserveOperandSpace(2);
449    BitSelect->addIncoming(FRes, Compute);
450    BitSelect->addIncoming(NewRes, Reverse);
451    ReturnInst::Create(BitSelect, CurBB);
452  }
453
454  // Return a call to the implementation function
455  Value *Args[] = {
456    CI->getOperand(1),
457    CI->getOperand(2),
458    CI->getOperand(3)
459  };
460  return CallInst::Create(F, Args, array_endof(Args), CI->getName(), CI);
461}
462
463/// Convert the llvm.part.set.iX.iY.iZ intrinsic. This intrinsic takes
464/// four integer arguments (iAny %Value, iAny %Replacement, i32 %Low, i32 %High)
465/// The first two arguments can be any bit width. The result is the same width
466/// as %Value. The operation replaces bits between %Low and %High with the value
467/// in %Replacement. If %Replacement is not the same width, it is truncated or
468/// zero extended as appropriate to fit the bits being replaced. If %Low is
469/// greater than %High then the inverse set of bits are replaced.
470/// @brief Lowering of llvm.bit.part.set intrinsic.
471static Instruction *LowerPartSet(CallInst *CI) {
472  // Make sure we're dealing with a part select intrinsic here
473  Function *F = CI->getCalledFunction();
474  const FunctionType *FT = F->getFunctionType();
475  if (!F->isDeclaration() || !FT->getReturnType()->isInteger() ||
476      FT->getNumParams() != 4 || !FT->getParamType(0)->isInteger() ||
477      !FT->getParamType(1)->isInteger() || !FT->getParamType(2)->isInteger() ||
478      !FT->getParamType(3)->isInteger())
479    return CI;
480
481  // Get the intrinsic implementation function by converting all the . to _
482  // in the intrinsic's function name and then reconstructing the function
483  // declaration.
484  std::string Name(F->getName());
485  for (unsigned i = 4; i < Name.length(); ++i)
486    if (Name[i] == '.')
487      Name[i] = '_';
488  Module* M = F->getParent();
489  F = cast<Function>(M->getOrInsertFunction(Name, FT));
490  F->setLinkage(GlobalValue::WeakLinkage);
491
492  // If we haven't defined the impl function yet, do so now
493  if (F->isDeclaration()) {
494    // Get the arguments for the function.
495    Function::arg_iterator args = F->arg_begin();
496    Value* Val = args++; Val->setName("Val");
497    Value* Rep = args++; Rep->setName("Rep");
498    Value* Lo  = args++; Lo->setName("Lo");
499    Value* Hi  = args++; Hi->setName("Hi");
500
501    // Get some types we need
502    const IntegerType* ValTy = cast<IntegerType>(Val->getType());
503    const IntegerType* RepTy = cast<IntegerType>(Rep->getType());
504    uint32_t ValBits = ValTy->getBitWidth();
505    uint32_t RepBits = RepTy->getBitWidth();
506
507    // Constant Definitions
508    ConstantInt* RepBitWidth = ConstantInt::get(Type::Int32Ty, RepBits);
509    ConstantInt* RepMask = ConstantInt::getAllOnesValue(RepTy);
510    ConstantInt* ValMask = ConstantInt::getAllOnesValue(ValTy);
511    ConstantInt* One = ConstantInt::get(Type::Int32Ty, 1);
512    ConstantInt* ValOne = ConstantInt::get(ValTy, 1);
513    ConstantInt* Zero = ConstantInt::get(Type::Int32Ty, 0);
514    ConstantInt* ValZero = ConstantInt::get(ValTy, 0);
515
516    // Basic blocks we fill in below.
517    BasicBlock* entry = BasicBlock::Create("entry", F, 0);
518    BasicBlock* large = BasicBlock::Create("large", F, 0);
519    BasicBlock* small = BasicBlock::Create("small", F, 0);
520    BasicBlock* reverse = BasicBlock::Create("reverse", F, 0);
521    BasicBlock* result = BasicBlock::Create("result", F, 0);
522
523    // BASIC BLOCK: entry
524    // First, get the number of bits that we're placing as an i32
525    ICmpInst* is_forward =
526      new ICmpInst(ICmpInst::ICMP_ULT, Lo, Hi, "", entry);
527    SelectInst* Hi_pn = SelectInst::Create(is_forward, Hi, Lo, "", entry);
528    SelectInst* Lo_pn = SelectInst::Create(is_forward, Lo, Hi, "", entry);
529    BinaryOperator* NumBits = BinaryOperator::CreateSub(Hi_pn, Lo_pn, "",entry);
530    NumBits = BinaryOperator::CreateAdd(NumBits, One, "", entry);
531    // Now, convert Lo and Hi to ValTy bit width
532    if (ValBits > 32) {
533      Lo = new ZExtInst(Lo_pn, ValTy, "", entry);
534    } else if (ValBits < 32) {
535      Lo = new TruncInst(Lo_pn, ValTy, "", entry);
536    } else {
537      Lo = Lo_pn;
538    }
539    // Determine if the replacement bits are larger than the number of bits we
540    // are replacing and deal with it.
541    ICmpInst* is_large =
542      new ICmpInst(ICmpInst::ICMP_ULT, NumBits, RepBitWidth, "", entry);
543    BranchInst::Create(large, small, is_large, entry);
544
545    // BASIC BLOCK: large
546    Instruction* MaskBits =
547      BinaryOperator::CreateSub(RepBitWidth, NumBits, "", large);
548    MaskBits = CastInst::CreateIntegerCast(MaskBits, RepMask->getType(),
549                                           false, "", large);
550    BinaryOperator* Mask1 =
551      BinaryOperator::CreateLShr(RepMask, MaskBits, "", large);
552    BinaryOperator* Rep2 = BinaryOperator::CreateAnd(Mask1, Rep, "", large);
553    BranchInst::Create(small, large);
554
555    // BASIC BLOCK: small
556    PHINode* Rep3 = PHINode::Create(RepTy, "", small);
557    Rep3->reserveOperandSpace(2);
558    Rep3->addIncoming(Rep2, large);
559    Rep3->addIncoming(Rep, entry);
560    Value* Rep4 = Rep3;
561    if (ValBits > RepBits)
562      Rep4 = new ZExtInst(Rep3, ValTy, "", small);
563    else if (ValBits < RepBits)
564      Rep4 = new TruncInst(Rep3, ValTy, "", small);
565    BranchInst::Create(result, reverse, is_forward, small);
566
567    // BASIC BLOCK: reverse (reverses the bits of the replacement)
568    // Set up our loop counter as a PHI so we can decrement on each iteration.
569    // We will loop for the number of bits in the replacement value.
570    PHINode *Count = PHINode::Create(Type::Int32Ty, "count", reverse);
571    Count->reserveOperandSpace(2);
572    Count->addIncoming(NumBits, small);
573
574    // Get the value that we are shifting bits out of as a PHI because
575    // we'll change this with each iteration.
576    PHINode *BitsToShift = PHINode::Create(Val->getType(), "val", reverse);
577    BitsToShift->reserveOperandSpace(2);
578    BitsToShift->addIncoming(Rep4, small);
579
580    // Get the result of the last computation or zero on first iteration
581    PHINode *RRes = PHINode::Create(Val->getType(), "rres", reverse);
582    RRes->reserveOperandSpace(2);
583    RRes->addIncoming(ValZero, small);
584
585    // Decrement the loop counter by one
586    Instruction *Decr = BinaryOperator::CreateSub(Count, One, "", reverse);
587    Count->addIncoming(Decr, reverse);
588
589    // Get the bit that we want to move into the result
590    Value *Bit = BinaryOperator::CreateAnd(BitsToShift, ValOne, "", reverse);
591
592    // Compute the new value of the bits to shift for the next iteration.
593    Value *NewVal = BinaryOperator::CreateLShr(BitsToShift, ValOne,"", reverse);
594    BitsToShift->addIncoming(NewVal, reverse);
595
596    // Shift the bit we extracted into the low bit of the result.
597    Instruction *NewRes = BinaryOperator::CreateShl(RRes, ValOne, "", reverse);
598    NewRes = BinaryOperator::CreateOr(NewRes, Bit, "", reverse);
599    RRes->addIncoming(NewRes, reverse);
600
601    // Terminate loop if we've moved all the bits.
602    ICmpInst *Cond = new ICmpInst(ICmpInst::ICMP_EQ, Decr, Zero, "", reverse);
603    BranchInst::Create(result, reverse, Cond, reverse);
604
605    // BASIC BLOCK: result
606    PHINode *Rplcmnt = PHINode::Create(Val->getType(), "", result);
607    Rplcmnt->reserveOperandSpace(2);
608    Rplcmnt->addIncoming(NewRes, reverse);
609    Rplcmnt->addIncoming(Rep4, small);
610    Value* t0   = CastInst::CreateIntegerCast(NumBits,ValTy,false,"",result);
611    Value* t1   = BinaryOperator::CreateShl(ValMask, Lo, "", result);
612    Value* t2   = BinaryOperator::CreateNot(t1, "", result);
613    Value* t3   = BinaryOperator::CreateShl(t1, t0, "", result);
614    Value* t4   = BinaryOperator::CreateOr(t2, t3, "", result);
615    Value* t5   = BinaryOperator::CreateAnd(t4, Val, "", result);
616    Value* t6   = BinaryOperator::CreateShl(Rplcmnt, Lo, "", result);
617    Value* Rslt = BinaryOperator::CreateOr(t5, t6, "part_set", result);
618    ReturnInst::Create(Rslt, result);
619  }
620
621  // Return a call to the implementation function
622  Value *Args[] = {
623    CI->getOperand(1),
624    CI->getOperand(2),
625    CI->getOperand(3),
626    CI->getOperand(4)
627  };
628  return CallInst::Create(F, Args, array_endof(Args), CI->getName(), CI);
629}
630
631static void ReplaceFPIntrinsicWithCall(CallInst *CI, Constant *FCache,
632                                       Constant *DCache, Constant *LDCache,
633                                       const char *Fname, const char *Dname,
634                                       const char *LDname) {
635  switch (CI->getOperand(1)->getType()->getTypeID()) {
636  default: assert(0 && "Invalid type in intrinsic"); abort();
637  case Type::FloatTyID:
638    ReplaceCallWith(Fname, CI, CI->op_begin()+1, CI->op_end(),
639                  Type::FloatTy, FCache);
640    break;
641  case Type::DoubleTyID:
642    ReplaceCallWith(Dname, CI, CI->op_begin()+1, CI->op_end(),
643                  Type::DoubleTy, DCache);
644    break;
645  case Type::X86_FP80TyID:
646  case Type::FP128TyID:
647  case Type::PPC_FP128TyID:
648    ReplaceCallWith(LDname, CI, CI->op_begin()+1, CI->op_end(),
649                  CI->getOperand(1)->getType(), LDCache);
650    break;
651  }
652}
653
654void IntrinsicLowering::LowerIntrinsicCall(CallInst *CI) {
655  Function *Callee = CI->getCalledFunction();
656  assert(Callee && "Cannot lower an indirect call!");
657
658  switch (Callee->getIntrinsicID()) {
659  case Intrinsic::not_intrinsic:
660    cerr << "Cannot lower a call to a non-intrinsic function '"
661         << Callee->getName() << "'!\n";
662    abort();
663  default:
664    cerr << "Error: Code generator does not support intrinsic function '"
665         << Callee->getName() << "'!\n";
666    abort();
667
668    // The setjmp/longjmp intrinsics should only exist in the code if it was
669    // never optimized (ie, right out of the CFE), or if it has been hacked on
670    // by the lowerinvoke pass.  In both cases, the right thing to do is to
671    // convert the call to an explicit setjmp or longjmp call.
672  case Intrinsic::setjmp: {
673    static Constant *SetjmpFCache = 0;
674    Value *V = ReplaceCallWith("setjmp", CI, CI->op_begin()+1, CI->op_end(),
675                               Type::Int32Ty, SetjmpFCache);
676    if (CI->getType() != Type::VoidTy)
677      CI->replaceAllUsesWith(V);
678    break;
679  }
680  case Intrinsic::sigsetjmp:
681     if (CI->getType() != Type::VoidTy)
682       CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
683     break;
684
685  case Intrinsic::longjmp: {
686    static Constant *LongjmpFCache = 0;
687    ReplaceCallWith("longjmp", CI, CI->op_begin()+1, CI->op_end(),
688                    Type::VoidTy, LongjmpFCache);
689    break;
690  }
691
692  case Intrinsic::siglongjmp: {
693    // Insert the call to abort
694    static Constant *AbortFCache = 0;
695    ReplaceCallWith("abort", CI, CI->op_end(), CI->op_end(),
696                    Type::VoidTy, AbortFCache);
697    break;
698  }
699  case Intrinsic::ctpop:
700    CI->replaceAllUsesWith(LowerCTPOP(CI->getOperand(1), CI));
701    break;
702
703  case Intrinsic::bswap:
704    CI->replaceAllUsesWith(LowerBSWAP(CI->getOperand(1), CI));
705    break;
706
707  case Intrinsic::ctlz:
708    CI->replaceAllUsesWith(LowerCTLZ(CI->getOperand(1), CI));
709    break;
710
711  case Intrinsic::cttz: {
712    // cttz(x) -> ctpop(~X & (X-1))
713    Value *Src = CI->getOperand(1);
714    Value *NotSrc = BinaryOperator::CreateNot(Src, Src->getName()+".not", CI);
715    Value *SrcM1 = ConstantInt::get(Src->getType(), 1);
716    SrcM1 = BinaryOperator::CreateSub(Src, SrcM1, "", CI);
717    Src = LowerCTPOP(BinaryOperator::CreateAnd(NotSrc, SrcM1, "", CI), CI);
718    CI->replaceAllUsesWith(Src);
719    break;
720  }
721
722  case Intrinsic::part_select:
723    CI->replaceAllUsesWith(LowerPartSelect(CI));
724    break;
725
726  case Intrinsic::part_set:
727    CI->replaceAllUsesWith(LowerPartSet(CI));
728    break;
729
730  case Intrinsic::stacksave:
731  case Intrinsic::stackrestore: {
732    static bool Warned = false;
733    if (!Warned)
734      cerr << "WARNING: this target does not support the llvm.stack"
735           << (Callee->getIntrinsicID() == Intrinsic::stacksave ?
736               "save" : "restore") << " intrinsic.\n";
737    Warned = true;
738    if (Callee->getIntrinsicID() == Intrinsic::stacksave)
739      CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
740    break;
741  }
742
743  case Intrinsic::returnaddress:
744  case Intrinsic::frameaddress:
745    cerr << "WARNING: this target does not support the llvm."
746         << (Callee->getIntrinsicID() == Intrinsic::returnaddress ?
747             "return" : "frame") << "address intrinsic.\n";
748    CI->replaceAllUsesWith(ConstantPointerNull::get(
749                                            cast<PointerType>(CI->getType())));
750    break;
751
752  case Intrinsic::prefetch:
753    break;    // Simply strip out prefetches on unsupported architectures
754
755  case Intrinsic::pcmarker:
756    break;    // Simply strip out pcmarker on unsupported architectures
757  case Intrinsic::readcyclecounter: {
758    cerr << "WARNING: this target does not support the llvm.readcyclecoun"
759         << "ter intrinsic.  It is being lowered to a constant 0\n";
760    CI->replaceAllUsesWith(ConstantInt::get(Type::Int64Ty, 0));
761    break;
762  }
763
764  case Intrinsic::dbg_stoppoint:
765  case Intrinsic::dbg_region_start:
766  case Intrinsic::dbg_region_end:
767  case Intrinsic::dbg_func_start:
768  case Intrinsic::dbg_declare:
769    break;    // Simply strip out debugging intrinsics
770
771  case Intrinsic::eh_exception:
772  case Intrinsic::eh_selector_i32:
773  case Intrinsic::eh_selector_i64:
774    CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
775    break;
776
777  case Intrinsic::eh_typeid_for_i32:
778  case Intrinsic::eh_typeid_for_i64:
779    // Return something different to eh_selector.
780    CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
781    break;
782
783  case Intrinsic::var_annotation:
784    break;   // Strip out annotate intrinsic
785
786  case Intrinsic::memcpy: {
787    static Constant *MemcpyFCache = 0;
788    Value *Size = CI->getOperand(3);
789    const Type *IntPtr = TD.getIntPtrType();
790    if (Size->getType()->getPrimitiveSizeInBits() <
791        IntPtr->getPrimitiveSizeInBits())
792      Size = new ZExtInst(Size, IntPtr, "", CI);
793    else if (Size->getType()->getPrimitiveSizeInBits() >
794             IntPtr->getPrimitiveSizeInBits())
795      Size = new TruncInst(Size, IntPtr, "", CI);
796    Value *Ops[3];
797    Ops[0] = CI->getOperand(1);
798    Ops[1] = CI->getOperand(2);
799    Ops[2] = Size;
800    ReplaceCallWith("memcpy", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
801                    MemcpyFCache);
802    break;
803  }
804  case Intrinsic::memmove: {
805    static Constant *MemmoveFCache = 0;
806    Value *Size = CI->getOperand(3);
807    const Type *IntPtr = TD.getIntPtrType();
808    if (Size->getType()->getPrimitiveSizeInBits() <
809        IntPtr->getPrimitiveSizeInBits())
810      Size = new ZExtInst(Size, IntPtr, "", CI);
811    else if (Size->getType()->getPrimitiveSizeInBits() >
812             IntPtr->getPrimitiveSizeInBits())
813      Size = new TruncInst(Size, IntPtr, "", CI);
814    Value *Ops[3];
815    Ops[0] = CI->getOperand(1);
816    Ops[1] = CI->getOperand(2);
817    Ops[2] = Size;
818    ReplaceCallWith("memmove", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
819                    MemmoveFCache);
820    break;
821  }
822  case Intrinsic::memset: {
823    static Constant *MemsetFCache = 0;
824    Value *Size = CI->getOperand(3);
825    const Type *IntPtr = TD.getIntPtrType();
826    if (Size->getType()->getPrimitiveSizeInBits() <
827        IntPtr->getPrimitiveSizeInBits())
828      Size = new ZExtInst(Size, IntPtr, "", CI);
829    else if (Size->getType()->getPrimitiveSizeInBits() >
830             IntPtr->getPrimitiveSizeInBits())
831      Size = new TruncInst(Size, IntPtr, "", CI);
832    Value *Ops[3];
833    Ops[0] = CI->getOperand(1);
834    // Extend the amount to i32.
835    Ops[1] = new ZExtInst(CI->getOperand(2), Type::Int32Ty, "", CI);
836    Ops[2] = Size;
837    ReplaceCallWith("memset", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
838                    MemsetFCache);
839    break;
840  }
841  case Intrinsic::sqrt: {
842    static Constant *sqrtFCache = 0;
843    static Constant *sqrtDCache = 0;
844    static Constant *sqrtLDCache = 0;
845    ReplaceFPIntrinsicWithCall(CI, sqrtFCache, sqrtDCache, sqrtLDCache,
846                               "sqrtf", "sqrt", "sqrtl");
847    break;
848  }
849  case Intrinsic::log: {
850    static Constant *logFCache = 0;
851    static Constant *logDCache = 0;
852    static Constant *logLDCache = 0;
853    ReplaceFPIntrinsicWithCall(CI, logFCache, logDCache, logLDCache,
854                               "logf", "log", "logl");
855    break;
856  }
857  case Intrinsic::log2: {
858    static Constant *log2FCache = 0;
859    static Constant *log2DCache = 0;
860    static Constant *log2LDCache = 0;
861    ReplaceFPIntrinsicWithCall(CI, log2FCache, log2DCache, log2LDCache,
862                               "log2f", "log2", "log2l");
863    break;
864  }
865  case Intrinsic::log10: {
866    static Constant *log10FCache = 0;
867    static Constant *log10DCache = 0;
868    static Constant *log10LDCache = 0;
869    ReplaceFPIntrinsicWithCall(CI, log10FCache, log10DCache, log10LDCache,
870                               "log10f", "log10", "log10l");
871    break;
872  }
873  case Intrinsic::exp: {
874    static Constant *expFCache = 0;
875    static Constant *expDCache = 0;
876    static Constant *expLDCache = 0;
877    ReplaceFPIntrinsicWithCall(CI, expFCache, expDCache, expLDCache,
878                               "expf", "exp", "expl");
879    break;
880  }
881  case Intrinsic::exp2: {
882    static Constant *exp2FCache = 0;
883    static Constant *exp2DCache = 0;
884    static Constant *exp2LDCache = 0;
885    ReplaceFPIntrinsicWithCall(CI, exp2FCache, exp2DCache, exp2LDCache,
886                               "exp2f", "exp2", "exp2l");
887    break;
888  }
889  case Intrinsic::pow: {
890    static Constant *powFCache = 0;
891    static Constant *powDCache = 0;
892    static Constant *powLDCache = 0;
893    ReplaceFPIntrinsicWithCall(CI, powFCache, powDCache, powLDCache,
894                               "powf", "pow", "powl");
895    break;
896  }
897  case Intrinsic::flt_rounds:
898     // Lower to "round to the nearest"
899     if (CI->getType() != Type::VoidTy)
900       CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
901     break;
902  }
903
904  assert(CI->use_empty() &&
905         "Lowering should have eliminated any uses of the intrinsic call!");
906  CI->eraseFromParent();
907}
908