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