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