remove llvm.part.set.* and llvm.part.select.*. They have never been
[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/Support/ErrorHandling.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/ADT/SmallVector.h"
23 using namespace llvm;
24
25 template <class ArgIt>
26 static void EnsureFunctionExists(Module &M, const char *Name,
27                                  ArgIt ArgBegin, ArgIt ArgEnd,
28                                  const Type *RetTy) {
29   // Insert a correctly-typed definition now.
30   std::vector<const Type *> ParamTys;
31   for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
32     ParamTys.push_back(I->getType());
33   M.getOrInsertFunction(Name, FunctionType::get(RetTy, ParamTys, false));
34 }
35
36 static void EnsureFPIntrinsicsExist(Module &M, Function *Fn,
37                                     const char *FName,
38                                     const char *DName, const char *LDName) {
39   // Insert definitions for all the floating point types.
40   switch((int)Fn->arg_begin()->getType()->getTypeID()) {
41   case Type::FloatTyID:
42     EnsureFunctionExists(M, FName, Fn->arg_begin(), Fn->arg_end(),
43                          Type::FloatTy);
44     break;
45   case Type::DoubleTyID:
46     EnsureFunctionExists(M, DName, Fn->arg_begin(), Fn->arg_end(),
47                          Type::DoubleTy);
48     break;
49   case Type::X86_FP80TyID:
50   case Type::FP128TyID:
51   case Type::PPC_FP128TyID:
52     EnsureFunctionExists(M, LDName, Fn->arg_begin(), Fn->arg_end(),
53                          Fn->arg_begin()->getType());
54     break;
55   }
56 }
57
58 /// ReplaceCallWith - This function is used when we want to lower an intrinsic
59 /// call to a call of an external function.  This handles hard cases such as
60 /// when there was already a prototype for the external function, and if that
61 /// prototype doesn't match the arguments we expect to pass in.
62 template <class ArgIt>
63 static CallInst *ReplaceCallWith(const char *NewFn, CallInst *CI,
64                                  ArgIt ArgBegin, ArgIt ArgEnd,
65                                  const Type *RetTy) {
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   Constant* FCache = M->getOrInsertFunction(NewFn,
74                                   FunctionType::get(RetTy, ParamTys, false));
75
76   IRBuilder<> Builder(CI->getParent(), CI);
77   SmallVector<Value *, 8> Args(ArgBegin, ArgEnd);
78   CallInst *NewCI = Builder.CreateCall(FCache, Args.begin(), Args.end());
79   NewCI->setName(CI->getName());
80   if (!CI->use_empty())
81     CI->replaceAllUsesWith(NewCI);
82   return NewCI;
83 }
84
85 void IntrinsicLowering::AddPrototypes(Module &M) {
86   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
87     if (I->isDeclaration() && !I->use_empty())
88       switch (I->getIntrinsicID()) {
89       default: break;
90       case Intrinsic::setjmp:
91         EnsureFunctionExists(M, "setjmp", I->arg_begin(), I->arg_end(),
92                              Type::Int32Ty);
93         break;
94       case Intrinsic::longjmp:
95         EnsureFunctionExists(M, "longjmp", I->arg_begin(), I->arg_end(),
96                              Type::VoidTy);
97         break;
98       case Intrinsic::siglongjmp:
99         EnsureFunctionExists(M, "abort", I->arg_end(), I->arg_end(),
100                              Type::VoidTy);
101         break;
102       case Intrinsic::memcpy:
103         M.getOrInsertFunction("memcpy", PointerType::getUnqual(Type::Int8Ty),
104                               PointerType::getUnqual(Type::Int8Ty), 
105                               PointerType::getUnqual(Type::Int8Ty), 
106                               TD.getIntPtrType(), (Type *)0);
107         break;
108       case Intrinsic::memmove:
109         M.getOrInsertFunction("memmove", PointerType::getUnqual(Type::Int8Ty),
110                               PointerType::getUnqual(Type::Int8Ty), 
111                               PointerType::getUnqual(Type::Int8Ty), 
112                               TD.getIntPtrType(), (Type *)0);
113         break;
114       case Intrinsic::memset:
115         M.getOrInsertFunction("memset", PointerType::getUnqual(Type::Int8Ty),
116                               PointerType::getUnqual(Type::Int8Ty), 
117                               Type::Int32Ty, 
118                               TD.getIntPtrType(), (Type *)0);
119         break;
120       case Intrinsic::sqrt:
121         EnsureFPIntrinsicsExist(M, I, "sqrtf", "sqrt", "sqrtl");
122         break;
123       case Intrinsic::sin:
124         EnsureFPIntrinsicsExist(M, I, "sinf", "sin", "sinl");
125         break;
126       case Intrinsic::cos:
127         EnsureFPIntrinsicsExist(M, I, "cosf", "cos", "cosl");
128         break;
129       case Intrinsic::pow:
130         EnsureFPIntrinsicsExist(M, I, "powf", "pow", "powl");
131         break;
132       case Intrinsic::log:
133         EnsureFPIntrinsicsExist(M, I, "logf", "log", "logl");
134         break;
135       case Intrinsic::log2:
136         EnsureFPIntrinsicsExist(M, I, "log2f", "log2", "log2l");
137         break;
138       case Intrinsic::log10:
139         EnsureFPIntrinsicsExist(M, I, "log10f", "log10", "log10l");
140         break;
141       case Intrinsic::exp:
142         EnsureFPIntrinsicsExist(M, I, "expf", "exp", "expl");
143         break;
144       case Intrinsic::exp2:
145         EnsureFPIntrinsicsExist(M, I, "exp2f", "exp2", "exp2l");
146         break;
147       }
148 }
149
150 /// LowerBSWAP - Emit the code to lower bswap of V before the specified
151 /// instruction IP.
152 static Value *LowerBSWAP(Value *V, Instruction *IP) {
153   assert(V->getType()->isInteger() && "Can't bswap a non-integer type!");
154
155   unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
156   
157   IRBuilder<> Builder(IP->getParent(), IP);
158
159   switch(BitSize) {
160   default: LLVM_UNREACHABLE("Unhandled type size of value to byteswap!");
161   case 16: {
162     Value *Tmp1 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 8),
163                                     "bswap.2");
164     Value *Tmp2 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 8),
165                                      "bswap.1");
166     V = Builder.CreateOr(Tmp1, Tmp2, "bswap.i16");
167     break;
168   }
169   case 32: {
170     Value *Tmp4 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 24),
171                                     "bswap.4");
172     Value *Tmp3 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 8),
173                                     "bswap.3");
174     Value *Tmp2 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 8),
175                                      "bswap.2");
176     Value *Tmp1 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 24),
177                                      "bswap.1");
178     Tmp3 = Builder.CreateAnd(Tmp3, ConstantInt::get(Type::Int32Ty, 0xFF0000),
179                              "bswap.and3");
180     Tmp2 = Builder.CreateAnd(Tmp2, ConstantInt::get(Type::Int32Ty, 0xFF00),
181                              "bswap.and2");
182     Tmp4 = Builder.CreateOr(Tmp4, Tmp3, "bswap.or1");
183     Tmp2 = Builder.CreateOr(Tmp2, Tmp1, "bswap.or2");
184     V = Builder.CreateOr(Tmp4, Tmp2, "bswap.i32");
185     break;
186   }
187   case 64: {
188     Value *Tmp8 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 56),
189                                     "bswap.8");
190     Value *Tmp7 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 40),
191                                     "bswap.7");
192     Value *Tmp6 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 24),
193                                     "bswap.6");
194     Value *Tmp5 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 8),
195                                     "bswap.5");
196     Value* Tmp4 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 8),
197                                      "bswap.4");
198     Value* Tmp3 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 24),
199                                      "bswap.3");
200     Value* Tmp2 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 40),
201                                      "bswap.2");
202     Value* Tmp1 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 56),
203                                      "bswap.1");
204     Tmp7 = Builder.CreateAnd(Tmp7,
205                              ConstantInt::get(Type::Int64Ty,
206                                               0xFF000000000000ULL),
207                              "bswap.and7");
208     Tmp6 = Builder.CreateAnd(Tmp6,
209                              ConstantInt::get(Type::Int64Ty,
210                                               0xFF0000000000ULL),
211                              "bswap.and6");
212     Tmp5 = Builder.CreateAnd(Tmp5,
213                              ConstantInt::get(Type::Int64Ty, 0xFF00000000ULL),
214                              "bswap.and5");
215     Tmp4 = Builder.CreateAnd(Tmp4,
216                              ConstantInt::get(Type::Int64Ty, 0xFF000000ULL),
217                              "bswap.and4");
218     Tmp3 = Builder.CreateAnd(Tmp3,
219                              ConstantInt::get(Type::Int64Ty, 0xFF0000ULL),
220                              "bswap.and3");
221     Tmp2 = Builder.CreateAnd(Tmp2,
222                              ConstantInt::get(Type::Int64Ty, 0xFF00ULL),
223                              "bswap.and2");
224     Tmp8 = Builder.CreateOr(Tmp8, Tmp7, "bswap.or1");
225     Tmp6 = Builder.CreateOr(Tmp6, Tmp5, "bswap.or2");
226     Tmp4 = Builder.CreateOr(Tmp4, Tmp3, "bswap.or3");
227     Tmp2 = Builder.CreateOr(Tmp2, Tmp1, "bswap.or4");
228     Tmp8 = Builder.CreateOr(Tmp8, Tmp6, "bswap.or5");
229     Tmp4 = Builder.CreateOr(Tmp4, Tmp2, "bswap.or6");
230     V = Builder.CreateOr(Tmp8, Tmp4, "bswap.i64");
231     break;
232   }
233   }
234   return V;
235 }
236
237 /// LowerCTPOP - Emit the code to lower ctpop of V before the specified
238 /// instruction IP.
239 static Value *LowerCTPOP(Value *V, Instruction *IP) {
240   assert(V->getType()->isInteger() && "Can't ctpop a non-integer type!");
241
242   static const uint64_t MaskValues[6] = {
243     0x5555555555555555ULL, 0x3333333333333333ULL,
244     0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
245     0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
246   };
247
248   IRBuilder<> Builder(IP->getParent(), IP);
249
250   unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
251   unsigned WordSize = (BitSize + 63) / 64;
252   Value *Count = ConstantInt::get(V->getType(), 0);
253
254   for (unsigned n = 0; n < WordSize; ++n) {
255     Value *PartValue = V;
256     for (unsigned i = 1, ct = 0; i < (BitSize>64 ? 64 : BitSize); 
257          i <<= 1, ++ct) {
258       Value *MaskCst = ConstantInt::get(V->getType(), MaskValues[ct]);
259       Value *LHS = Builder.CreateAnd(PartValue, MaskCst, "cppop.and1");
260       Value *VShift = Builder.CreateLShr(PartValue,
261                                          ConstantInt::get(V->getType(), i),
262                                          "ctpop.sh");
263       Value *RHS = Builder.CreateAnd(VShift, MaskCst, "cppop.and2");
264       PartValue = Builder.CreateAdd(LHS, RHS, "ctpop.step");
265     }
266     Count = Builder.CreateAdd(PartValue, Count, "ctpop.part");
267     if (BitSize > 64) {
268       V = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 64),
269                              "ctpop.part.sh");
270       BitSize -= 64;
271     }
272   }
273
274   return Count;
275 }
276
277 /// LowerCTLZ - Emit the code to lower ctlz of V before the specified
278 /// instruction IP.
279 static Value *LowerCTLZ(Value *V, Instruction *IP) {
280
281   IRBuilder<> Builder(IP->getParent(), IP);
282
283   unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
284   for (unsigned i = 1; i < BitSize; i <<= 1) {
285     Value *ShVal = ConstantInt::get(V->getType(), i);
286     ShVal = Builder.CreateLShr(V, ShVal, "ctlz.sh");
287     V = Builder.CreateOr(V, ShVal, "ctlz.step");
288   }
289
290   V = Builder.CreateNot(V);
291   return LowerCTPOP(V, IP);
292 }
293
294 static void ReplaceFPIntrinsicWithCall(CallInst *CI, const char *Fname,
295                                        const char *Dname,
296                                        const char *LDname) {
297   switch (CI->getOperand(1)->getType()->getTypeID()) {
298   default: LLVM_UNREACHABLE( "Invalid type in intrinsic");
299   case Type::FloatTyID:
300     ReplaceCallWith(Fname, CI, CI->op_begin() + 1, CI->op_end(),
301                   Type::FloatTy);
302     break;
303   case Type::DoubleTyID:
304     ReplaceCallWith(Dname, CI, CI->op_begin() + 1, CI->op_end(),
305                   Type::DoubleTy);
306     break;
307   case Type::X86_FP80TyID:
308   case Type::FP128TyID:
309   case Type::PPC_FP128TyID:
310     ReplaceCallWith(LDname, CI, CI->op_begin() + 1, CI->op_end(),
311                   CI->getOperand(1)->getType());
312     break;
313   }
314 }
315
316 void IntrinsicLowering::LowerIntrinsicCall(CallInst *CI) {
317   IRBuilder<> Builder(CI->getParent(), CI);
318
319   Function *Callee = CI->getCalledFunction();
320   assert(Callee && "Cannot lower an indirect call!");
321
322   switch (Callee->getIntrinsicID()) {
323   case Intrinsic::not_intrinsic:
324     llvm_report_error("Cannot lower a call to a non-intrinsic function '"+
325                       Callee->getName() + "'!");
326   default:
327     llvm_report_error("Code generator does not support intrinsic function '"+
328                       Callee->getName()+"'!");
329
330     // The setjmp/longjmp intrinsics should only exist in the code if it was
331     // never optimized (ie, right out of the CFE), or if it has been hacked on
332     // by the lowerinvoke pass.  In both cases, the right thing to do is to
333     // convert the call to an explicit setjmp or longjmp call.
334   case Intrinsic::setjmp: {
335     Value *V = ReplaceCallWith("setjmp", CI, CI->op_begin() + 1, CI->op_end(),
336                                Type::Int32Ty);
337     if (CI->getType() != Type::VoidTy)
338       CI->replaceAllUsesWith(V);
339     break;
340   }
341   case Intrinsic::sigsetjmp:
342      if (CI->getType() != Type::VoidTy)
343        CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
344      break;
345
346   case Intrinsic::longjmp: {
347     ReplaceCallWith("longjmp", CI, CI->op_begin() + 1, CI->op_end(),
348                     Type::VoidTy);
349     break;
350   }
351
352   case Intrinsic::siglongjmp: {
353     // Insert the call to abort
354     ReplaceCallWith("abort", CI, CI->op_end(), CI->op_end(), 
355                     Type::VoidTy);
356     break;
357   }
358   case Intrinsic::ctpop:
359     CI->replaceAllUsesWith(LowerCTPOP(CI->getOperand(1), CI));
360     break;
361
362   case Intrinsic::bswap:
363     CI->replaceAllUsesWith(LowerBSWAP(CI->getOperand(1), CI));
364     break;
365     
366   case Intrinsic::ctlz:
367     CI->replaceAllUsesWith(LowerCTLZ(CI->getOperand(1), CI));
368     break;
369
370   case Intrinsic::cttz: {
371     // cttz(x) -> ctpop(~X & (X-1))
372     Value *Src = CI->getOperand(1);
373     Value *NotSrc = Builder.CreateNot(Src);
374     NotSrc->setName(Src->getName() + ".not");
375     Value *SrcM1 = ConstantInt::get(Src->getType(), 1);
376     SrcM1 = Builder.CreateSub(Src, SrcM1);
377     Src = LowerCTPOP(Builder.CreateAnd(NotSrc, SrcM1), CI);
378     CI->replaceAllUsesWith(Src);
379     break;
380   }
381
382   case Intrinsic::stacksave:
383   case Intrinsic::stackrestore: {
384     if (!Warned)
385       cerr << "WARNING: this target does not support the llvm.stack"
386            << (Callee->getIntrinsicID() == Intrinsic::stacksave ?
387                "save" : "restore") << " intrinsic.\n";
388     Warned = true;
389     if (Callee->getIntrinsicID() == Intrinsic::stacksave)
390       CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
391     break;
392   }
393     
394   case Intrinsic::returnaddress:
395   case Intrinsic::frameaddress:
396     cerr << "WARNING: this target does not support the llvm."
397          << (Callee->getIntrinsicID() == Intrinsic::returnaddress ?
398              "return" : "frame") << "address intrinsic.\n";
399     CI->replaceAllUsesWith(ConstantPointerNull::get(
400                                             cast<PointerType>(CI->getType())));
401     break;
402
403   case Intrinsic::prefetch:
404     break;    // Simply strip out prefetches on unsupported architectures
405
406   case Intrinsic::pcmarker:
407     break;    // Simply strip out pcmarker on unsupported architectures
408   case Intrinsic::readcyclecounter: {
409     cerr << "WARNING: this target does not support the llvm.readcyclecoun"
410          << "ter intrinsic.  It is being lowered to a constant 0\n";
411     CI->replaceAllUsesWith(ConstantInt::get(Type::Int64Ty, 0));
412     break;
413   }
414
415   case Intrinsic::dbg_stoppoint:
416   case Intrinsic::dbg_region_start:
417   case Intrinsic::dbg_region_end:
418   case Intrinsic::dbg_func_start:
419   case Intrinsic::dbg_declare:
420     break;    // Simply strip out debugging intrinsics
421
422   case Intrinsic::eh_exception:
423   case Intrinsic::eh_selector_i32:
424   case Intrinsic::eh_selector_i64:
425     CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
426     break;
427
428   case Intrinsic::eh_typeid_for_i32:
429   case Intrinsic::eh_typeid_for_i64:
430     // Return something different to eh_selector.
431     CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
432     break;
433
434   case Intrinsic::var_annotation:
435     break;   // Strip out annotate intrinsic
436     
437   case Intrinsic::memcpy: {
438     const IntegerType *IntPtr = TD.getIntPtrType();
439     Value *Size = Builder.CreateIntCast(CI->getOperand(3), IntPtr,
440                                         /* isSigned */ false);
441     Value *Ops[3];
442     Ops[0] = CI->getOperand(1);
443     Ops[1] = CI->getOperand(2);
444     Ops[2] = Size;
445     ReplaceCallWith("memcpy", CI, Ops, Ops+3, CI->getOperand(1)->getType());
446     break;
447   }
448   case Intrinsic::memmove: {
449     const IntegerType *IntPtr = TD.getIntPtrType();
450     Value *Size = Builder.CreateIntCast(CI->getOperand(3), IntPtr,
451                                         /* isSigned */ false);
452     Value *Ops[3];
453     Ops[0] = CI->getOperand(1);
454     Ops[1] = CI->getOperand(2);
455     Ops[2] = Size;
456     ReplaceCallWith("memmove", CI, Ops, Ops+3, CI->getOperand(1)->getType());
457     break;
458   }
459   case Intrinsic::memset: {
460     const IntegerType *IntPtr = TD.getIntPtrType();
461     Value *Size = Builder.CreateIntCast(CI->getOperand(3), IntPtr,
462                                         /* isSigned */ false);
463     Value *Ops[3];
464     Ops[0] = CI->getOperand(1);
465     // Extend the amount to i32.
466     Ops[1] = Builder.CreateIntCast(CI->getOperand(2), Type::Int32Ty,
467                                    /* isSigned */ false);
468     Ops[2] = Size;
469     ReplaceCallWith("memset", CI, Ops, Ops+3, CI->getOperand(1)->getType());
470     break;
471   }
472   case Intrinsic::sqrt: {
473     ReplaceFPIntrinsicWithCall(CI, "sqrtf", "sqrt", "sqrtl");
474     break;
475   }
476   case Intrinsic::log: {
477     ReplaceFPIntrinsicWithCall(CI, "logf", "log", "logl");
478     break;
479   }
480   case Intrinsic::log2: {
481     ReplaceFPIntrinsicWithCall(CI, "log2f", "log2", "log2l");
482     break;
483   }
484   case Intrinsic::log10: {
485     ReplaceFPIntrinsicWithCall(CI, "log10f", "log10", "log10l");
486     break;
487   }
488   case Intrinsic::exp: {
489     ReplaceFPIntrinsicWithCall(CI, "expf", "exp", "expl");
490     break;
491   }
492   case Intrinsic::exp2: {
493     ReplaceFPIntrinsicWithCall(CI, "exp2f", "exp2", "exp2l");
494     break;
495   }
496   case Intrinsic::pow: {
497     ReplaceFPIntrinsicWithCall(CI, "powf", "pow", "powl");
498     break;
499   }
500   case Intrinsic::flt_rounds:
501      // Lower to "round to the nearest"
502      if (CI->getType() != Type::VoidTy)
503        CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
504      break;
505   }
506
507   assert(CI->use_empty() &&
508          "Lowering should have eliminated any uses of the intrinsic call!");
509   CI->eraseFromParent();
510 }