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