Make mem[cpy,move,set] intrinsics overloaded.
[oota-llvm.git] / lib / CodeGen / IntrinsicLowering.cpp
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"
24 using namespace llvm;
25
26 template <class ArgIt>
27 static 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 static 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.
60 template <class ArgIt>
61 static 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
84 void 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.
151 static 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.
237 static 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.
275 static 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.
298 static 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.
471 static 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     }
537     // Determine if the replacement bits are larger than the number of bits we
538     // are replacing and deal with it.
539     ICmpInst* is_large = 
540       new ICmpInst(ICmpInst::ICMP_ULT, NumBits, RepBitWidth, "", entry);
541     BranchInst::Create(large, small, is_large, entry);
542
543     // BASIC BLOCK: large
544     Instruction* MaskBits = 
545       BinaryOperator::CreateSub(RepBitWidth, NumBits, "", large);
546     MaskBits = CastInst::CreateIntegerCast(MaskBits, RepMask->getType(), 
547                                            false, "", large);
548     BinaryOperator* Mask1 = 
549       BinaryOperator::CreateLShr(RepMask, MaskBits, "", large);
550     BinaryOperator* Rep2 = BinaryOperator::CreateAnd(Mask1, Rep, "", large);
551     BranchInst::Create(small, large);
552
553     // BASIC BLOCK: small
554     PHINode* Rep3 = PHINode::Create(RepTy, "", small);
555     Rep3->reserveOperandSpace(2);
556     Rep3->addIncoming(Rep2, large);
557     Rep3->addIncoming(Rep, entry);
558     Value* Rep4 = Rep3;
559     if (ValBits > RepBits)
560       Rep4 = new ZExtInst(Rep3, ValTy, "", small);
561     else if (ValBits < RepBits)
562       Rep4 = new TruncInst(Rep3, ValTy, "", small);
563     BranchInst::Create(result, reverse, is_forward, small);
564
565     // BASIC BLOCK: reverse (reverses the bits of the replacement)
566     // Set up our loop counter as a PHI so we can decrement on each iteration.
567     // We will loop for the number of bits in the replacement value.
568     PHINode *Count = PHINode::Create(Type::Int32Ty, "count", reverse);
569     Count->reserveOperandSpace(2);
570     Count->addIncoming(NumBits, small);
571
572     // Get the value that we are shifting bits out of as a PHI because
573     // we'll change this with each iteration.
574     PHINode *BitsToShift = PHINode::Create(Val->getType(), "val", reverse);
575     BitsToShift->reserveOperandSpace(2);
576     BitsToShift->addIncoming(Rep4, small);
577
578     // Get the result of the last computation or zero on first iteration
579     PHINode *RRes = PHINode::Create(Val->getType(), "rres", reverse);
580     RRes->reserveOperandSpace(2);
581     RRes->addIncoming(ValZero, small);
582
583     // Decrement the loop counter by one
584     Instruction *Decr = BinaryOperator::CreateSub(Count, One, "", reverse);
585     Count->addIncoming(Decr, reverse);
586
587     // Get the bit that we want to move into the result
588     Value *Bit = BinaryOperator::CreateAnd(BitsToShift, ValOne, "", reverse);
589
590     // Compute the new value of the bits to shift for the next iteration.
591     Value *NewVal = BinaryOperator::CreateLShr(BitsToShift, ValOne,"", reverse);
592     BitsToShift->addIncoming(NewVal, reverse);
593
594     // Shift the bit we extracted into the low bit of the result.
595     Instruction *NewRes = BinaryOperator::CreateShl(RRes, ValOne, "", reverse);
596     NewRes = BinaryOperator::CreateOr(NewRes, Bit, "", reverse);
597     RRes->addIncoming(NewRes, reverse);
598     
599     // Terminate loop if we've moved all the bits.
600     ICmpInst *Cond = new ICmpInst(ICmpInst::ICMP_EQ, Decr, Zero, "", reverse);
601     BranchInst::Create(result, reverse, Cond, reverse);
602
603     // BASIC BLOCK: result
604     PHINode *Rplcmnt = PHINode::Create(Val->getType(), "", result);
605     Rplcmnt->reserveOperandSpace(2);
606     Rplcmnt->addIncoming(NewRes, reverse);
607     Rplcmnt->addIncoming(Rep4, small);
608     Value* t0   = CastInst::CreateIntegerCast(NumBits,ValTy,false,"",result);
609     Value* t1   = BinaryOperator::CreateShl(ValMask, Lo, "", result);
610     Value* t2   = BinaryOperator::CreateNot(t1, "", result);
611     Value* t3   = BinaryOperator::CreateShl(t1, t0, "", result);
612     Value* t4   = BinaryOperator::CreateOr(t2, t3, "", result);
613     Value* t5   = BinaryOperator::CreateAnd(t4, Val, "", result);
614     Value* t6   = BinaryOperator::CreateShl(Rplcmnt, Lo, "", result);
615     Value* Rslt = BinaryOperator::CreateOr(t5, t6, "part_set", result);
616     ReturnInst::Create(Rslt, result);
617   }
618
619   // Return a call to the implementation function
620   Value *Args[] = {
621     CI->getOperand(1),
622     CI->getOperand(2),
623     CI->getOperand(3),
624     CI->getOperand(4)
625   };
626   return CallInst::Create(F, Args, array_endof(Args), CI->getName(), CI);
627 }
628
629 static void ReplaceFPIntrinsicWithCall(CallInst *CI, Constant *FCache,
630                                        Constant *DCache, Constant *LDCache,
631                                        const char *Fname, const char *Dname,
632                                        const char *LDname) {
633   switch (CI->getOperand(1)->getType()->getTypeID()) {
634   default: assert(0 && "Invalid type in intrinsic"); abort();
635   case Type::FloatTyID:
636     ReplaceCallWith(Fname, CI, CI->op_begin()+1, CI->op_end(),
637                   Type::FloatTy, FCache);
638     break;
639   case Type::DoubleTyID:
640     ReplaceCallWith(Dname, CI, CI->op_begin()+1, CI->op_end(),
641                   Type::DoubleTy, DCache);
642     break;
643   case Type::X86_FP80TyID:
644   case Type::FP128TyID:
645   case Type::PPC_FP128TyID:
646     ReplaceCallWith(LDname, CI, CI->op_begin()+1, CI->op_end(),
647                   CI->getOperand(1)->getType(), LDCache);
648     break;
649   }
650 }
651
652 void IntrinsicLowering::LowerIntrinsicCall(CallInst *CI) {
653   Function *Callee = CI->getCalledFunction();
654   assert(Callee && "Cannot lower an indirect call!");
655
656   switch (Callee->getIntrinsicID()) {
657   case Intrinsic::not_intrinsic:
658     cerr << "Cannot lower a call to a non-intrinsic function '"
659          << Callee->getName() << "'!\n";
660     abort();
661   default:
662     cerr << "Error: Code generator does not support intrinsic function '"
663          << Callee->getName() << "'!\n";
664     abort();
665
666     // The setjmp/longjmp intrinsics should only exist in the code if it was
667     // never optimized (ie, right out of the CFE), or if it has been hacked on
668     // by the lowerinvoke pass.  In both cases, the right thing to do is to
669     // convert the call to an explicit setjmp or longjmp call.
670   case Intrinsic::setjmp: {
671     static Constant *SetjmpFCache = 0;
672     Value *V = ReplaceCallWith("setjmp", CI, CI->op_begin()+1, CI->op_end(),
673                                Type::Int32Ty, SetjmpFCache);
674     if (CI->getType() != Type::VoidTy)
675       CI->replaceAllUsesWith(V);
676     break;
677   }
678   case Intrinsic::sigsetjmp:
679      if (CI->getType() != Type::VoidTy)
680        CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
681      break;
682
683   case Intrinsic::longjmp: {
684     static Constant *LongjmpFCache = 0;
685     ReplaceCallWith("longjmp", CI, CI->op_begin()+1, CI->op_end(),
686                     Type::VoidTy, LongjmpFCache);
687     break;
688   }
689
690   case Intrinsic::siglongjmp: {
691     // Insert the call to abort
692     static Constant *AbortFCache = 0;
693     ReplaceCallWith("abort", CI, CI->op_end(), CI->op_end(), 
694                     Type::VoidTy, AbortFCache);
695     break;
696   }
697   case Intrinsic::ctpop:
698     CI->replaceAllUsesWith(LowerCTPOP(CI->getOperand(1), CI));
699     break;
700
701   case Intrinsic::bswap:
702     CI->replaceAllUsesWith(LowerBSWAP(CI->getOperand(1), CI));
703     break;
704     
705   case Intrinsic::ctlz:
706     CI->replaceAllUsesWith(LowerCTLZ(CI->getOperand(1), CI));
707     break;
708
709   case Intrinsic::cttz: {
710     // cttz(x) -> ctpop(~X & (X-1))
711     Value *Src = CI->getOperand(1);
712     Value *NotSrc = BinaryOperator::CreateNot(Src, Src->getName()+".not", CI);
713     Value *SrcM1 = ConstantInt::get(Src->getType(), 1);
714     SrcM1 = BinaryOperator::CreateSub(Src, SrcM1, "", CI);
715     Src = LowerCTPOP(BinaryOperator::CreateAnd(NotSrc, SrcM1, "", CI), CI);
716     CI->replaceAllUsesWith(Src);
717     break;
718   }
719
720   case Intrinsic::part_select:
721     CI->replaceAllUsesWith(LowerPartSelect(CI));
722     break;
723
724   case Intrinsic::part_set:
725     CI->replaceAllUsesWith(LowerPartSet(CI));
726     break;
727
728   case Intrinsic::stacksave:
729   case Intrinsic::stackrestore: {
730     static bool Warned = false;
731     if (!Warned)
732       cerr << "WARNING: this target does not support the llvm.stack"
733            << (Callee->getIntrinsicID() == Intrinsic::stacksave ?
734                "save" : "restore") << " intrinsic.\n";
735     Warned = true;
736     if (Callee->getIntrinsicID() == Intrinsic::stacksave)
737       CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
738     break;
739   }
740     
741   case Intrinsic::returnaddress:
742   case Intrinsic::frameaddress:
743     cerr << "WARNING: this target does not support the llvm."
744          << (Callee->getIntrinsicID() == Intrinsic::returnaddress ?
745              "return" : "frame") << "address intrinsic.\n";
746     CI->replaceAllUsesWith(ConstantPointerNull::get(
747                                             cast<PointerType>(CI->getType())));
748     break;
749
750   case Intrinsic::prefetch:
751     break;    // Simply strip out prefetches on unsupported architectures
752
753   case Intrinsic::pcmarker:
754     break;    // Simply strip out pcmarker on unsupported architectures
755   case Intrinsic::readcyclecounter: {
756     cerr << "WARNING: this target does not support the llvm.readcyclecoun"
757          << "ter intrinsic.  It is being lowered to a constant 0\n";
758     CI->replaceAllUsesWith(ConstantInt::get(Type::Int64Ty, 0));
759     break;
760   }
761
762   case Intrinsic::dbg_stoppoint:
763   case Intrinsic::dbg_region_start:
764   case Intrinsic::dbg_region_end:
765   case Intrinsic::dbg_func_start:
766   case Intrinsic::dbg_declare:
767     break;    // Simply strip out debugging intrinsics
768
769   case Intrinsic::eh_exception:
770   case Intrinsic::eh_selector_i32:
771   case Intrinsic::eh_selector_i64:
772     CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
773     break;
774
775   case Intrinsic::eh_typeid_for_i32:
776   case Intrinsic::eh_typeid_for_i64:
777     // Return something different to eh_selector.
778     CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
779     break;
780
781   case Intrinsic::var_annotation:
782     break;   // Strip out annotate intrinsic
783     
784   case Intrinsic::memcpy: {
785     static Constant *MemcpyFCache = 0;
786     Value *Size = CI->getOperand(3);
787     const Type *IntPtr = TD.getIntPtrType();
788     if (Size->getType()->getPrimitiveSizeInBits() <
789         IntPtr->getPrimitiveSizeInBits())
790       Size = new ZExtInst(Size, IntPtr, "", CI);
791     else if (Size->getType()->getPrimitiveSizeInBits() >
792              IntPtr->getPrimitiveSizeInBits())
793       Size = new TruncInst(Size, IntPtr, "", CI);
794     Value *Ops[3];
795     Ops[0] = CI->getOperand(1);
796     Ops[1] = CI->getOperand(2);
797     Ops[2] = Size;
798     ReplaceCallWith("memcpy", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
799                     MemcpyFCache);
800     break;
801   }
802   case Intrinsic::memmove: {
803     static Constant *MemmoveFCache = 0;
804     Value *Size = CI->getOperand(3);
805     const Type *IntPtr = TD.getIntPtrType();
806     if (Size->getType()->getPrimitiveSizeInBits() <
807         IntPtr->getPrimitiveSizeInBits())
808       Size = new ZExtInst(Size, IntPtr, "", CI);
809     else if (Size->getType()->getPrimitiveSizeInBits() >
810              IntPtr->getPrimitiveSizeInBits())
811       Size = new TruncInst(Size, IntPtr, "", CI);
812     Value *Ops[3];
813     Ops[0] = CI->getOperand(1);
814     Ops[1] = CI->getOperand(2);
815     Ops[2] = Size;
816     ReplaceCallWith("memmove", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
817                     MemmoveFCache);
818     break;
819   }
820   case Intrinsic::memset: {
821     static Constant *MemsetFCache = 0;
822     Value *Size = CI->getOperand(3);
823     const Type *IntPtr = TD.getIntPtrType();
824     if (Size->getType()->getPrimitiveSizeInBits() <
825         IntPtr->getPrimitiveSizeInBits())
826       Size = new ZExtInst(Size, IntPtr, "", CI);
827     else if (Size->getType()->getPrimitiveSizeInBits() >
828              IntPtr->getPrimitiveSizeInBits())
829       Size = new TruncInst(Size, IntPtr, "", CI);
830     Value *Ops[3];
831     Ops[0] = CI->getOperand(1);
832     // Extend the amount to i32.
833     Ops[1] = new ZExtInst(CI->getOperand(2), Type::Int32Ty, "", CI);
834     Ops[2] = Size;
835     ReplaceCallWith("memset", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
836                     MemsetFCache);
837     break;
838   }
839   case Intrinsic::sqrt: {
840     static Constant *sqrtFCache = 0;
841     static Constant *sqrtDCache = 0;
842     static Constant *sqrtLDCache = 0;
843     ReplaceFPIntrinsicWithCall(CI, sqrtFCache, sqrtDCache, sqrtLDCache,
844                                "sqrtf", "sqrt", "sqrtl");
845     break;
846   }
847   case Intrinsic::log: {
848     static Constant *logFCache = 0;
849     static Constant *logDCache = 0;
850     static Constant *logLDCache = 0;
851     ReplaceFPIntrinsicWithCall(CI, logFCache, logDCache, logLDCache,
852                                "logf", "log", "logl");
853     break;
854   }
855   case Intrinsic::log2: {
856     static Constant *log2FCache = 0;
857     static Constant *log2DCache = 0;
858     static Constant *log2LDCache = 0;
859     ReplaceFPIntrinsicWithCall(CI, log2FCache, log2DCache, log2LDCache,
860                                "log2f", "log2", "log2l");
861     break;
862   }
863   case Intrinsic::log10: {
864     static Constant *log10FCache = 0;
865     static Constant *log10DCache = 0;
866     static Constant *log10LDCache = 0;
867     ReplaceFPIntrinsicWithCall(CI, log10FCache, log10DCache, log10LDCache,
868                                "log10f", "log10", "log10l");
869     break;
870   }
871   case Intrinsic::exp: {
872     static Constant *expFCache = 0;
873     static Constant *expDCache = 0;
874     static Constant *expLDCache = 0;
875     ReplaceFPIntrinsicWithCall(CI, expFCache, expDCache, expLDCache,
876                                "expf", "exp", "expl");
877     break;
878   }
879   case Intrinsic::exp2: {
880     static Constant *exp2FCache = 0;
881     static Constant *exp2DCache = 0;
882     static Constant *exp2LDCache = 0;
883     ReplaceFPIntrinsicWithCall(CI, exp2FCache, exp2DCache, exp2LDCache,
884                                "exp2f", "exp2", "exp2l");
885     break;
886   }
887   case Intrinsic::pow: {
888     static Constant *powFCache = 0;
889     static Constant *powDCache = 0;
890     static Constant *powLDCache = 0;
891     ReplaceFPIntrinsicWithCall(CI, powFCache, powDCache, powLDCache,
892                                "powf", "pow", "powl");
893     break;
894   }
895   case Intrinsic::flt_rounds:
896      // Lower to "round to the nearest"
897      if (CI->getType() != Type::VoidTy)
898        CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
899      break;
900   }
901
902   assert(CI->use_empty() &&
903          "Lowering should have eliminated any uses of the intrinsic call!");
904   CI->eraseFromParent();
905 }