1 //===-- IntrinsicLowering.cpp - Intrinsic Lowering default implementation -===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the IntrinsicLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Module.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Type.h"
19 #include "llvm/CodeGen/IntrinsicLowering.h"
20 #include "llvm/Support/Streams.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/STLExtras.h"
26 template <class ArgIt>
27 static void EnsureFunctionExists(Module &M, const char *Name,
28 ArgIt ArgBegin, ArgIt ArgEnd,
30 // Insert a correctly-typed definition now.
31 std::vector<const Type *> ParamTys;
32 for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
33 ParamTys.push_back(I->getType());
34 M.getOrInsertFunction(Name, FunctionType::get(RetTy, ParamTys, false));
37 /// ReplaceCallWith - This function is used when we want to lower an intrinsic
38 /// call to a call of an external function. This handles hard cases such as
39 /// when there was already a prototype for the external function, and if that
40 /// prototype doesn't match the arguments we expect to pass in.
41 template <class ArgIt>
42 static CallInst *ReplaceCallWith(const char *NewFn, CallInst *CI,
43 ArgIt ArgBegin, ArgIt ArgEnd,
44 const Type *RetTy, Constant *&FCache) {
46 // If we haven't already looked up this function, check to see if the
47 // program already contains a function with this name.
48 Module *M = CI->getParent()->getParent()->getParent();
49 // Get or insert the definition now.
50 std::vector<const Type *> ParamTys;
51 for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
52 ParamTys.push_back((*I)->getType());
53 FCache = M->getOrInsertFunction(NewFn,
54 FunctionType::get(RetTy, ParamTys, false));
57 SmallVector<Value *, 8> Args(ArgBegin, ArgEnd);
58 CallInst *NewCI = new CallInst(FCache, Args.begin(), Args.end(),
61 CI->replaceAllUsesWith(NewCI);
65 void IntrinsicLowering::AddPrototypes(Module &M) {
66 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
67 if (I->isDeclaration() && !I->use_empty())
68 switch (I->getIntrinsicID()) {
70 case Intrinsic::setjmp:
71 EnsureFunctionExists(M, "setjmp", I->arg_begin(), I->arg_end(),
74 case Intrinsic::longjmp:
75 EnsureFunctionExists(M, "longjmp", I->arg_begin(), I->arg_end(),
78 case Intrinsic::siglongjmp:
79 EnsureFunctionExists(M, "abort", I->arg_end(), I->arg_end(),
82 case Intrinsic::memcpy_i32:
83 case Intrinsic::memcpy_i64:
84 M.getOrInsertFunction("memcpy", PointerType::getUnqual(Type::Int8Ty),
85 PointerType::getUnqual(Type::Int8Ty),
86 PointerType::getUnqual(Type::Int8Ty),
87 TD.getIntPtrType(), (Type *)0);
89 case Intrinsic::memmove_i32:
90 case Intrinsic::memmove_i64:
91 M.getOrInsertFunction("memmove", PointerType::getUnqual(Type::Int8Ty),
92 PointerType::getUnqual(Type::Int8Ty),
93 PointerType::getUnqual(Type::Int8Ty),
94 TD.getIntPtrType(), (Type *)0);
96 case Intrinsic::memset_i32:
97 case Intrinsic::memset_i64:
98 M.getOrInsertFunction("memset", PointerType::getUnqual(Type::Int8Ty),
99 PointerType::getUnqual(Type::Int8Ty),
101 TD.getIntPtrType(), (Type *)0);
103 case Intrinsic::sqrt:
104 switch((int)I->arg_begin()->getType()->getTypeID()) {
105 case Type::FloatTyID:
106 EnsureFunctionExists(M, "sqrtf", I->arg_begin(), I->arg_end(),
108 case Type::DoubleTyID:
109 EnsureFunctionExists(M, "sqrt", I->arg_begin(), I->arg_end(),
111 case Type::X86_FP80TyID:
112 case Type::FP128TyID:
113 case Type::PPC_FP128TyID:
114 EnsureFunctionExists(M, "sqrtl", I->arg_begin(), I->arg_end(),
115 I->arg_begin()->getType());
119 switch((int)I->arg_begin()->getType()->getTypeID()) {
120 case Type::FloatTyID:
121 EnsureFunctionExists(M, "sinf", I->arg_begin(), I->arg_end(),
123 case Type::DoubleTyID:
124 EnsureFunctionExists(M, "sin", I->arg_begin(), I->arg_end(),
126 case Type::X86_FP80TyID:
127 case Type::FP128TyID:
128 case Type::PPC_FP128TyID:
129 EnsureFunctionExists(M, "sinl", I->arg_begin(), I->arg_end(),
130 I->arg_begin()->getType());
134 switch((int)I->arg_begin()->getType()->getTypeID()) {
135 case Type::FloatTyID:
136 EnsureFunctionExists(M, "cosf", I->arg_begin(), I->arg_end(),
138 case Type::DoubleTyID:
139 EnsureFunctionExists(M, "cos", I->arg_begin(), I->arg_end(),
141 case Type::X86_FP80TyID:
142 case Type::FP128TyID:
143 case Type::PPC_FP128TyID:
144 EnsureFunctionExists(M, "cosl", I->arg_begin(), I->arg_end(),
145 I->arg_begin()->getType());
149 switch((int)I->arg_begin()->getType()->getTypeID()) {
150 case Type::FloatTyID:
151 EnsureFunctionExists(M, "powf", I->arg_begin(), I->arg_end(),
153 case Type::DoubleTyID:
154 EnsureFunctionExists(M, "pow", I->arg_begin(), I->arg_end(),
156 case Type::X86_FP80TyID:
157 case Type::FP128TyID:
158 case Type::PPC_FP128TyID:
159 EnsureFunctionExists(M, "powl", I->arg_begin(), I->arg_end(),
160 I->arg_begin()->getType());
166 /// LowerBSWAP - Emit the code to lower bswap of V before the specified
168 static Value *LowerBSWAP(Value *V, Instruction *IP) {
169 assert(V->getType()->isInteger() && "Can't bswap a non-integer type!");
171 unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
174 default: assert(0 && "Unhandled type size of value to byteswap!");
176 Value *Tmp1 = BinaryOperator::createShl(V,
177 ConstantInt::get(V->getType(),8),"bswap.2",IP);
178 Value *Tmp2 = BinaryOperator::createLShr(V,
179 ConstantInt::get(V->getType(),8),"bswap.1",IP);
180 V = BinaryOperator::createOr(Tmp1, Tmp2, "bswap.i16", IP);
184 Value *Tmp4 = BinaryOperator::createShl(V,
185 ConstantInt::get(V->getType(),24),"bswap.4", IP);
186 Value *Tmp3 = BinaryOperator::createShl(V,
187 ConstantInt::get(V->getType(),8),"bswap.3",IP);
188 Value *Tmp2 = BinaryOperator::createLShr(V,
189 ConstantInt::get(V->getType(),8),"bswap.2",IP);
190 Value *Tmp1 = BinaryOperator::createLShr(V,
191 ConstantInt::get(V->getType(),24),"bswap.1", IP);
192 Tmp3 = BinaryOperator::createAnd(Tmp3,
193 ConstantInt::get(Type::Int32Ty, 0xFF0000),
195 Tmp2 = BinaryOperator::createAnd(Tmp2,
196 ConstantInt::get(Type::Int32Ty, 0xFF00),
198 Tmp4 = BinaryOperator::createOr(Tmp4, Tmp3, "bswap.or1", IP);
199 Tmp2 = BinaryOperator::createOr(Tmp2, Tmp1, "bswap.or2", IP);
200 V = BinaryOperator::createOr(Tmp4, Tmp2, "bswap.i32", IP);
204 Value *Tmp8 = BinaryOperator::createShl(V,
205 ConstantInt::get(V->getType(),56),"bswap.8", IP);
206 Value *Tmp7 = BinaryOperator::createShl(V,
207 ConstantInt::get(V->getType(),40),"bswap.7", IP);
208 Value *Tmp6 = BinaryOperator::createShl(V,
209 ConstantInt::get(V->getType(),24),"bswap.6", IP);
210 Value *Tmp5 = BinaryOperator::createShl(V,
211 ConstantInt::get(V->getType(),8),"bswap.5", IP);
212 Value* Tmp4 = BinaryOperator::createLShr(V,
213 ConstantInt::get(V->getType(),8),"bswap.4", IP);
214 Value* Tmp3 = BinaryOperator::createLShr(V,
215 ConstantInt::get(V->getType(),24),"bswap.3", IP);
216 Value* Tmp2 = BinaryOperator::createLShr(V,
217 ConstantInt::get(V->getType(),40),"bswap.2", IP);
218 Value* Tmp1 = BinaryOperator::createLShr(V,
219 ConstantInt::get(V->getType(),56),"bswap.1", IP);
220 Tmp7 = BinaryOperator::createAnd(Tmp7,
221 ConstantInt::get(Type::Int64Ty,
222 0xFF000000000000ULL),
224 Tmp6 = BinaryOperator::createAnd(Tmp6,
225 ConstantInt::get(Type::Int64Ty, 0xFF0000000000ULL),
227 Tmp5 = BinaryOperator::createAnd(Tmp5,
228 ConstantInt::get(Type::Int64Ty, 0xFF00000000ULL),
230 Tmp4 = BinaryOperator::createAnd(Tmp4,
231 ConstantInt::get(Type::Int64Ty, 0xFF000000ULL),
233 Tmp3 = BinaryOperator::createAnd(Tmp3,
234 ConstantInt::get(Type::Int64Ty, 0xFF0000ULL),
236 Tmp2 = BinaryOperator::createAnd(Tmp2,
237 ConstantInt::get(Type::Int64Ty, 0xFF00ULL),
239 Tmp8 = BinaryOperator::createOr(Tmp8, Tmp7, "bswap.or1", IP);
240 Tmp6 = BinaryOperator::createOr(Tmp6, Tmp5, "bswap.or2", IP);
241 Tmp4 = BinaryOperator::createOr(Tmp4, Tmp3, "bswap.or3", IP);
242 Tmp2 = BinaryOperator::createOr(Tmp2, Tmp1, "bswap.or4", IP);
243 Tmp8 = BinaryOperator::createOr(Tmp8, Tmp6, "bswap.or5", IP);
244 Tmp4 = BinaryOperator::createOr(Tmp4, Tmp2, "bswap.or6", IP);
245 V = BinaryOperator::createOr(Tmp8, Tmp4, "bswap.i64", IP);
252 /// LowerCTPOP - Emit the code to lower ctpop of V before the specified
254 static Value *LowerCTPOP(Value *V, Instruction *IP) {
255 assert(V->getType()->isInteger() && "Can't ctpop a non-integer type!");
257 static const uint64_t MaskValues[6] = {
258 0x5555555555555555ULL, 0x3333333333333333ULL,
259 0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
260 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
263 unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
264 unsigned WordSize = (BitSize + 63) / 64;
265 Value *Count = ConstantInt::get(V->getType(), 0);
267 for (unsigned n = 0; n < WordSize; ++n) {
268 Value *PartValue = V;
269 for (unsigned i = 1, ct = 0; i < (BitSize>64 ? 64 : BitSize);
271 Value *MaskCst = ConstantInt::get(V->getType(), MaskValues[ct]);
272 Value *LHS = BinaryOperator::createAnd(
273 PartValue, MaskCst, "cppop.and1", IP);
274 Value *VShift = BinaryOperator::createLShr(PartValue,
275 ConstantInt::get(V->getType(), i), "ctpop.sh", IP);
276 Value *RHS = BinaryOperator::createAnd(VShift, MaskCst, "cppop.and2", IP);
277 PartValue = BinaryOperator::createAdd(LHS, RHS, "ctpop.step", IP);
279 Count = BinaryOperator::createAdd(PartValue, Count, "ctpop.part", IP);
281 V = BinaryOperator::createLShr(V, ConstantInt::get(V->getType(), 64),
282 "ctpop.part.sh", IP);
290 /// LowerCTLZ - Emit the code to lower ctlz of V before the specified
292 static Value *LowerCTLZ(Value *V, Instruction *IP) {
294 unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
295 for (unsigned i = 1; i < BitSize; i <<= 1) {
296 Value *ShVal = ConstantInt::get(V->getType(), i);
297 ShVal = BinaryOperator::createLShr(V, ShVal, "ctlz.sh", IP);
298 V = BinaryOperator::createOr(V, ShVal, "ctlz.step", IP);
301 V = BinaryOperator::createNot(V, "", IP);
302 return LowerCTPOP(V, IP);
305 /// Convert the llvm.part.select.iX.iY intrinsic. This intrinsic takes
306 /// three integer arguments. The first argument is the Value from which the
307 /// bits will be selected. It may be of any bit width. The second and third
308 /// arguments specify a range of bits to select with the second argument
309 /// specifying the low bit and the third argument specifying the high bit. Both
310 /// must be type i32. The result is the corresponding selected bits from the
311 /// Value in the same width as the Value (first argument). If the low bit index
312 /// is higher than the high bit index then the inverse selection is done and
313 /// the bits are returned in inverse order.
314 /// @brief Lowering of llvm.part.select intrinsic.
315 static Instruction *LowerPartSelect(CallInst *CI) {
316 // Make sure we're dealing with a part select intrinsic here
317 Function *F = CI->getCalledFunction();
318 const FunctionType *FT = F->getFunctionType();
319 if (!F->isDeclaration() || !FT->getReturnType()->isInteger() ||
320 FT->getNumParams() != 3 || !FT->getParamType(0)->isInteger() ||
321 !FT->getParamType(1)->isInteger() || !FT->getParamType(2)->isInteger())
324 // Get the intrinsic implementation function by converting all the . to _
325 // in the intrinsic's function name and then reconstructing the function
327 std::string Name(F->getName());
328 for (unsigned i = 4; i < Name.length(); ++i)
331 Module* M = F->getParent();
332 F = cast<Function>(M->getOrInsertFunction(Name, FT));
333 F->setLinkage(GlobalValue::WeakLinkage);
335 // If we haven't defined the impl function yet, do so now
336 if (F->isDeclaration()) {
338 // Get the arguments to the function
339 Function::arg_iterator args = F->arg_begin();
340 Value* Val = args++; Val->setName("Val");
341 Value* Lo = args++; Lo->setName("Lo");
342 Value* Hi = args++; Hi->setName("High");
344 // We want to select a range of bits here such that [Hi, Lo] is shifted
345 // down to the low bits. However, it is quite possible that Hi is smaller
346 // than Lo in which case the bits have to be reversed.
348 // Create the blocks we will need for the two cases (forward, reverse)
349 BasicBlock* CurBB = new BasicBlock("entry", F);
350 BasicBlock *RevSize = new BasicBlock("revsize", CurBB->getParent());
351 BasicBlock *FwdSize = new BasicBlock("fwdsize", CurBB->getParent());
352 BasicBlock *Compute = new BasicBlock("compute", CurBB->getParent());
353 BasicBlock *Reverse = new BasicBlock("reverse", CurBB->getParent());
354 BasicBlock *RsltBlk = new BasicBlock("result", CurBB->getParent());
356 // Cast Hi and Lo to the size of Val so the widths are all the same
357 if (Hi->getType() != Val->getType())
358 Hi = CastInst::createIntegerCast(Hi, Val->getType(), false,
360 if (Lo->getType() != Val->getType())
361 Lo = CastInst::createIntegerCast(Lo, Val->getType(), false,
364 // Compute a few things that both cases will need, up front.
365 Constant* Zero = ConstantInt::get(Val->getType(), 0);
366 Constant* One = ConstantInt::get(Val->getType(), 1);
367 Constant* AllOnes = ConstantInt::getAllOnesValue(Val->getType());
369 // Compare the Hi and Lo bit positions. This is used to determine
370 // which case we have (forward or reverse)
371 ICmpInst *Cmp = new ICmpInst(ICmpInst::ICMP_ULT, Hi, Lo, "less",CurBB);
372 new BranchInst(RevSize, FwdSize, Cmp, CurBB);
374 // First, copmute the number of bits in the forward case.
375 Instruction* FBitSize =
376 BinaryOperator::createSub(Hi, Lo,"fbits", FwdSize);
377 new BranchInst(Compute, FwdSize);
379 // Second, compute the number of bits in the reverse case.
380 Instruction* RBitSize =
381 BinaryOperator::createSub(Lo, Hi, "rbits", RevSize);
382 new BranchInst(Compute, RevSize);
384 // Now, compute the bit range. Start by getting the bitsize and the shift
385 // amount (either Hi or Lo) from PHI nodes. Then we compute a mask for
386 // the number of bits we want in the range. We shift the bits down to the
387 // least significant bits, apply the mask to zero out unwanted high bits,
388 // and we have computed the "forward" result. It may still need to be
391 // Get the BitSize from one of the two subtractions
392 PHINode *BitSize = new PHINode(Val->getType(), "bits", Compute);
393 BitSize->reserveOperandSpace(2);
394 BitSize->addIncoming(FBitSize, FwdSize);
395 BitSize->addIncoming(RBitSize, RevSize);
397 // Get the ShiftAmount as the smaller of Hi/Lo
398 PHINode *ShiftAmt = new PHINode(Val->getType(), "shiftamt", Compute);
399 ShiftAmt->reserveOperandSpace(2);
400 ShiftAmt->addIncoming(Lo, FwdSize);
401 ShiftAmt->addIncoming(Hi, RevSize);
403 // Increment the bit size
404 Instruction *BitSizePlusOne =
405 BinaryOperator::createAdd(BitSize, One, "bits", Compute);
407 // Create a Mask to zero out the high order bits.
409 BinaryOperator::createShl(AllOnes, BitSizePlusOne, "mask", Compute);
410 Mask = BinaryOperator::createNot(Mask, "mask", Compute);
412 // Shift the bits down and apply the mask
414 BinaryOperator::createLShr(Val, ShiftAmt, "fres", Compute);
415 FRes = BinaryOperator::createAnd(FRes, Mask, "fres", Compute);
416 new BranchInst(Reverse, RsltBlk, Cmp, Compute);
418 // In the Reverse block we have the mask already in FRes but we must reverse
419 // it by shifting FRes bits right and putting them in RRes by shifting them
422 // First set up our loop counters
423 PHINode *Count = new PHINode(Val->getType(), "count", Reverse);
424 Count->reserveOperandSpace(2);
425 Count->addIncoming(BitSizePlusOne, Compute);
427 // Next, get the value that we are shifting.
428 PHINode *BitsToShift = new PHINode(Val->getType(), "val", Reverse);
429 BitsToShift->reserveOperandSpace(2);
430 BitsToShift->addIncoming(FRes, Compute);
432 // Finally, get the result of the last computation
433 PHINode *RRes = new PHINode(Val->getType(), "rres", Reverse);
434 RRes->reserveOperandSpace(2);
435 RRes->addIncoming(Zero, Compute);
437 // Decrement the counter
438 Instruction *Decr = BinaryOperator::createSub(Count, One, "decr", Reverse);
439 Count->addIncoming(Decr, Reverse);
441 // Compute the Bit that we want to move
443 BinaryOperator::createAnd(BitsToShift, One, "bit", Reverse);
445 // Compute the new value for next iteration.
446 Instruction *NewVal =
447 BinaryOperator::createLShr(BitsToShift, One, "rshift", Reverse);
448 BitsToShift->addIncoming(NewVal, Reverse);
450 // Shift the bit into the low bits of the result.
451 Instruction *NewRes =
452 BinaryOperator::createShl(RRes, One, "lshift", Reverse);
453 NewRes = BinaryOperator::createOr(NewRes, Bit, "addbit", Reverse);
454 RRes->addIncoming(NewRes, Reverse);
456 // Terminate loop if we've moved all the bits.
458 new ICmpInst(ICmpInst::ICMP_EQ, Decr, Zero, "cond", Reverse);
459 new BranchInst(RsltBlk, Reverse, Cond, Reverse);
461 // Finally, in the result block, select one of the two results with a PHI
462 // node and return the result;
464 PHINode *BitSelect = new PHINode(Val->getType(), "part_select", CurBB);
465 BitSelect->reserveOperandSpace(2);
466 BitSelect->addIncoming(FRes, Compute);
467 BitSelect->addIncoming(NewRes, Reverse);
468 new ReturnInst(BitSelect, CurBB);
471 // Return a call to the implementation function
477 return new CallInst(F, Args, array_endof(Args), CI->getName(), CI);
480 /// Convert the llvm.part.set.iX.iY.iZ intrinsic. This intrinsic takes
481 /// four integer arguments (iAny %Value, iAny %Replacement, i32 %Low, i32 %High)
482 /// The first two arguments can be any bit width. The result is the same width
483 /// as %Value. The operation replaces bits between %Low and %High with the value
484 /// in %Replacement. If %Replacement is not the same width, it is truncated or
485 /// zero extended as appropriate to fit the bits being replaced. If %Low is
486 /// greater than %High then the inverse set of bits are replaced.
487 /// @brief Lowering of llvm.bit.part.set intrinsic.
488 static Instruction *LowerPartSet(CallInst *CI) {
489 // Make sure we're dealing with a part select intrinsic here
490 Function *F = CI->getCalledFunction();
491 const FunctionType *FT = F->getFunctionType();
492 if (!F->isDeclaration() || !FT->getReturnType()->isInteger() ||
493 FT->getNumParams() != 4 || !FT->getParamType(0)->isInteger() ||
494 !FT->getParamType(1)->isInteger() || !FT->getParamType(2)->isInteger() ||
495 !FT->getParamType(3)->isInteger())
498 // Get the intrinsic implementation function by converting all the . to _
499 // in the intrinsic's function name and then reconstructing the function
501 std::string Name(F->getName());
502 for (unsigned i = 4; i < Name.length(); ++i)
505 Module* M = F->getParent();
506 F = cast<Function>(M->getOrInsertFunction(Name, FT));
507 F->setLinkage(GlobalValue::WeakLinkage);
509 // If we haven't defined the impl function yet, do so now
510 if (F->isDeclaration()) {
511 // Get the arguments for the function.
512 Function::arg_iterator args = F->arg_begin();
513 Value* Val = args++; Val->setName("Val");
514 Value* Rep = args++; Rep->setName("Rep");
515 Value* Lo = args++; Lo->setName("Lo");
516 Value* Hi = args++; Hi->setName("Hi");
518 // Get some types we need
519 const IntegerType* ValTy = cast<IntegerType>(Val->getType());
520 const IntegerType* RepTy = cast<IntegerType>(Rep->getType());
521 uint32_t ValBits = ValTy->getBitWidth();
522 uint32_t RepBits = RepTy->getBitWidth();
524 // Constant Definitions
525 ConstantInt* RepBitWidth = ConstantInt::get(Type::Int32Ty, RepBits);
526 ConstantInt* RepMask = ConstantInt::getAllOnesValue(RepTy);
527 ConstantInt* ValMask = ConstantInt::getAllOnesValue(ValTy);
528 ConstantInt* One = ConstantInt::get(Type::Int32Ty, 1);
529 ConstantInt* ValOne = ConstantInt::get(ValTy, 1);
530 ConstantInt* Zero = ConstantInt::get(Type::Int32Ty, 0);
531 ConstantInt* ValZero = ConstantInt::get(ValTy, 0);
533 // Basic blocks we fill in below.
534 BasicBlock* entry = new BasicBlock("entry", F, 0);
535 BasicBlock* large = new BasicBlock("large", F, 0);
536 BasicBlock* small = new BasicBlock("small", F, 0);
537 BasicBlock* reverse = new BasicBlock("reverse", F, 0);
538 BasicBlock* result = new BasicBlock("result", F, 0);
540 // BASIC BLOCK: entry
541 // First, get the number of bits that we're placing as an i32
542 ICmpInst* is_forward =
543 new ICmpInst(ICmpInst::ICMP_ULT, Lo, Hi, "", entry);
544 SelectInst* Hi_pn = new SelectInst(is_forward, Hi, Lo, "", entry);
545 SelectInst* Lo_pn = new SelectInst(is_forward, Lo, Hi, "", entry);
546 BinaryOperator* NumBits = BinaryOperator::createSub(Hi_pn, Lo_pn, "",entry);
547 NumBits = BinaryOperator::createAdd(NumBits, One, "", entry);
548 // Now, convert Lo and Hi to ValTy bit width
550 Lo = new ZExtInst(Lo_pn, ValTy, "", entry);
551 } else if (ValBits < 32) {
552 Lo = new TruncInst(Lo_pn, ValTy, "", entry);
554 // Determine if the replacement bits are larger than the number of bits we
555 // are replacing and deal with it.
557 new ICmpInst(ICmpInst::ICMP_ULT, NumBits, RepBitWidth, "", entry);
558 new BranchInst(large, small, is_large, entry);
560 // BASIC BLOCK: large
561 Instruction* MaskBits =
562 BinaryOperator::createSub(RepBitWidth, NumBits, "", large);
563 MaskBits = CastInst::createIntegerCast(MaskBits, RepMask->getType(),
565 BinaryOperator* Mask1 =
566 BinaryOperator::createLShr(RepMask, MaskBits, "", large);
567 BinaryOperator* Rep2 = BinaryOperator::createAnd(Mask1, Rep, "", large);
568 new BranchInst(small, large);
570 // BASIC BLOCK: small
571 PHINode* Rep3 = new PHINode(RepTy, "", small);
572 Rep3->reserveOperandSpace(2);
573 Rep3->addIncoming(Rep2, large);
574 Rep3->addIncoming(Rep, entry);
576 if (ValBits > RepBits)
577 Rep4 = new ZExtInst(Rep3, ValTy, "", small);
578 else if (ValBits < RepBits)
579 Rep4 = new TruncInst(Rep3, ValTy, "", small);
580 new BranchInst(result, reverse, is_forward, small);
582 // BASIC BLOCK: reverse (reverses the bits of the replacement)
583 // Set up our loop counter as a PHI so we can decrement on each iteration.
584 // We will loop for the number of bits in the replacement value.
585 PHINode *Count = new PHINode(Type::Int32Ty, "count", reverse);
586 Count->reserveOperandSpace(2);
587 Count->addIncoming(NumBits, small);
589 // Get the value that we are shifting bits out of as a PHI because
590 // we'll change this with each iteration.
591 PHINode *BitsToShift = new PHINode(Val->getType(), "val", reverse);
592 BitsToShift->reserveOperandSpace(2);
593 BitsToShift->addIncoming(Rep4, small);
595 // Get the result of the last computation or zero on first iteration
596 PHINode *RRes = new PHINode(Val->getType(), "rres", reverse);
597 RRes->reserveOperandSpace(2);
598 RRes->addIncoming(ValZero, small);
600 // Decrement the loop counter by one
601 Instruction *Decr = BinaryOperator::createSub(Count, One, "", reverse);
602 Count->addIncoming(Decr, reverse);
604 // Get the bit that we want to move into the result
605 Value *Bit = BinaryOperator::createAnd(BitsToShift, ValOne, "", reverse);
607 // Compute the new value of the bits to shift for the next iteration.
608 Value *NewVal = BinaryOperator::createLShr(BitsToShift, ValOne,"", reverse);
609 BitsToShift->addIncoming(NewVal, reverse);
611 // Shift the bit we extracted into the low bit of the result.
612 Instruction *NewRes = BinaryOperator::createShl(RRes, ValOne, "", reverse);
613 NewRes = BinaryOperator::createOr(NewRes, Bit, "", reverse);
614 RRes->addIncoming(NewRes, reverse);
616 // Terminate loop if we've moved all the bits.
617 ICmpInst *Cond = new ICmpInst(ICmpInst::ICMP_EQ, Decr, Zero, "", reverse);
618 new BranchInst(result, reverse, Cond, reverse);
620 // BASIC BLOCK: result
621 PHINode *Rplcmnt = new PHINode(Val->getType(), "", result);
622 Rplcmnt->reserveOperandSpace(2);
623 Rplcmnt->addIncoming(NewRes, reverse);
624 Rplcmnt->addIncoming(Rep4, small);
625 Value* t0 = CastInst::createIntegerCast(NumBits,ValTy,false,"",result);
626 Value* t1 = BinaryOperator::createShl(ValMask, Lo, "", result);
627 Value* t2 = BinaryOperator::createNot(t1, "", result);
628 Value* t3 = BinaryOperator::createShl(t1, t0, "", result);
629 Value* t4 = BinaryOperator::createOr(t2, t3, "", result);
630 Value* t5 = BinaryOperator::createAnd(t4, Val, "", result);
631 Value* t6 = BinaryOperator::createShl(Rplcmnt, Lo, "", result);
632 Value* Rslt = BinaryOperator::createOr(t5, t6, "part_set", result);
633 new ReturnInst(Rslt, result);
636 // Return a call to the implementation function
643 return new CallInst(F, Args, array_endof(Args), CI->getName(), CI);
647 void IntrinsicLowering::LowerIntrinsicCall(CallInst *CI) {
648 Function *Callee = CI->getCalledFunction();
649 assert(Callee && "Cannot lower an indirect call!");
651 switch (Callee->getIntrinsicID()) {
652 case Intrinsic::not_intrinsic:
653 cerr << "Cannot lower a call to a non-intrinsic function '"
654 << Callee->getName() << "'!\n";
657 cerr << "Error: Code generator does not support intrinsic function '"
658 << Callee->getName() << "'!\n";
661 // The setjmp/longjmp intrinsics should only exist in the code if it was
662 // never optimized (ie, right out of the CFE), or if it has been hacked on
663 // by the lowerinvoke pass. In both cases, the right thing to do is to
664 // convert the call to an explicit setjmp or longjmp call.
665 case Intrinsic::setjmp: {
666 static Constant *SetjmpFCache = 0;
667 Value *V = ReplaceCallWith("setjmp", CI, CI->op_begin()+1, CI->op_end(),
668 Type::Int32Ty, SetjmpFCache);
669 if (CI->getType() != Type::VoidTy)
670 CI->replaceAllUsesWith(V);
673 case Intrinsic::sigsetjmp:
674 if (CI->getType() != Type::VoidTy)
675 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
678 case Intrinsic::longjmp: {
679 static Constant *LongjmpFCache = 0;
680 ReplaceCallWith("longjmp", CI, CI->op_begin()+1, CI->op_end(),
681 Type::VoidTy, LongjmpFCache);
685 case Intrinsic::siglongjmp: {
686 // Insert the call to abort
687 static Constant *AbortFCache = 0;
688 ReplaceCallWith("abort", CI, CI->op_end(), CI->op_end(),
689 Type::VoidTy, AbortFCache);
692 case Intrinsic::ctpop:
693 CI->replaceAllUsesWith(LowerCTPOP(CI->getOperand(1), CI));
696 case Intrinsic::bswap:
697 CI->replaceAllUsesWith(LowerBSWAP(CI->getOperand(1), CI));
700 case Intrinsic::ctlz:
701 CI->replaceAllUsesWith(LowerCTLZ(CI->getOperand(1), CI));
704 case Intrinsic::cttz: {
705 // cttz(x) -> ctpop(~X & (X-1))
706 Value *Src = CI->getOperand(1);
707 Value *NotSrc = BinaryOperator::createNot(Src, Src->getName()+".not", CI);
708 Value *SrcM1 = ConstantInt::get(Src->getType(), 1);
709 SrcM1 = BinaryOperator::createSub(Src, SrcM1, "", CI);
710 Src = LowerCTPOP(BinaryOperator::createAnd(NotSrc, SrcM1, "", CI), CI);
711 CI->replaceAllUsesWith(Src);
715 case Intrinsic::part_select:
716 CI->replaceAllUsesWith(LowerPartSelect(CI));
719 case Intrinsic::part_set:
720 CI->replaceAllUsesWith(LowerPartSet(CI));
723 case Intrinsic::stacksave:
724 case Intrinsic::stackrestore: {
725 static bool Warned = false;
727 cerr << "WARNING: this target does not support the llvm.stack"
728 << (Callee->getIntrinsicID() == Intrinsic::stacksave ?
729 "save" : "restore") << " intrinsic.\n";
731 if (Callee->getIntrinsicID() == Intrinsic::stacksave)
732 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
736 case Intrinsic::returnaddress:
737 case Intrinsic::frameaddress:
738 cerr << "WARNING: this target does not support the llvm."
739 << (Callee->getIntrinsicID() == Intrinsic::returnaddress ?
740 "return" : "frame") << "address intrinsic.\n";
741 CI->replaceAllUsesWith(ConstantPointerNull::get(
742 cast<PointerType>(CI->getType())));
745 case Intrinsic::prefetch:
746 break; // Simply strip out prefetches on unsupported architectures
748 case Intrinsic::pcmarker:
749 break; // Simply strip out pcmarker on unsupported architectures
750 case Intrinsic::readcyclecounter: {
751 cerr << "WARNING: this target does not support the llvm.readcyclecoun"
752 << "ter intrinsic. It is being lowered to a constant 0\n";
753 CI->replaceAllUsesWith(ConstantInt::get(Type::Int64Ty, 0));
757 case Intrinsic::dbg_stoppoint:
758 case Intrinsic::dbg_region_start:
759 case Intrinsic::dbg_region_end:
760 case Intrinsic::dbg_func_start:
761 case Intrinsic::dbg_declare:
762 break; // Simply strip out debugging intrinsics
764 case Intrinsic::eh_exception:
765 case Intrinsic::eh_selector_i32:
766 case Intrinsic::eh_selector_i64:
767 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
770 case Intrinsic::eh_typeid_for_i32:
771 case Intrinsic::eh_typeid_for_i64:
772 // Return something different to eh_selector.
773 CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
776 case Intrinsic::var_annotation:
777 break; // Strip out annotate intrinsic
779 case Intrinsic::memcpy_i32:
780 case Intrinsic::memcpy_i64: {
781 static Constant *MemcpyFCache = 0;
782 Value *Size = CI->getOperand(3);
783 const Type *IntPtr = TD.getIntPtrType();
784 if (Size->getType()->getPrimitiveSizeInBits() <
785 IntPtr->getPrimitiveSizeInBits())
786 Size = new ZExtInst(Size, IntPtr, "", CI);
787 else if (Size->getType()->getPrimitiveSizeInBits() >
788 IntPtr->getPrimitiveSizeInBits())
789 Size = new TruncInst(Size, IntPtr, "", CI);
791 Ops[0] = CI->getOperand(1);
792 Ops[1] = CI->getOperand(2);
794 ReplaceCallWith("memcpy", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
798 case Intrinsic::memmove_i32:
799 case Intrinsic::memmove_i64: {
800 static Constant *MemmoveFCache = 0;
801 Value *Size = CI->getOperand(3);
802 const Type *IntPtr = TD.getIntPtrType();
803 if (Size->getType()->getPrimitiveSizeInBits() <
804 IntPtr->getPrimitiveSizeInBits())
805 Size = new ZExtInst(Size, IntPtr, "", CI);
806 else if (Size->getType()->getPrimitiveSizeInBits() >
807 IntPtr->getPrimitiveSizeInBits())
808 Size = new TruncInst(Size, IntPtr, "", CI);
810 Ops[0] = CI->getOperand(1);
811 Ops[1] = CI->getOperand(2);
813 ReplaceCallWith("memmove", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
817 case Intrinsic::memset_i32:
818 case Intrinsic::memset_i64: {
819 static Constant *MemsetFCache = 0;
820 Value *Size = CI->getOperand(3);
821 const Type *IntPtr = TD.getIntPtrType();
822 if (Size->getType()->getPrimitiveSizeInBits() <
823 IntPtr->getPrimitiveSizeInBits())
824 Size = new ZExtInst(Size, IntPtr, "", CI);
825 else if (Size->getType()->getPrimitiveSizeInBits() >
826 IntPtr->getPrimitiveSizeInBits())
827 Size = new TruncInst(Size, IntPtr, "", CI);
829 Ops[0] = CI->getOperand(1);
830 // Extend the amount to i32.
831 Ops[1] = new ZExtInst(CI->getOperand(2), Type::Int32Ty, "", CI);
833 ReplaceCallWith("memset", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
837 case Intrinsic::sqrt: {
838 static Constant *sqrtfFCache = 0;
839 static Constant *sqrtFCache = 0;
840 static Constant *sqrtLDCache = 0;
841 switch (CI->getOperand(1)->getType()->getTypeID()) {
842 default: assert(0 && "Invalid type in sqrt"); abort();
843 case Type::FloatTyID:
844 ReplaceCallWith("sqrtf", CI, CI->op_begin()+1, CI->op_end(),
845 Type::FloatTy, sqrtfFCache);
847 case Type::DoubleTyID:
848 ReplaceCallWith("sqrt", CI, CI->op_begin()+1, CI->op_end(),
849 Type::DoubleTy, sqrtFCache);
851 case Type::X86_FP80TyID:
852 case Type::FP128TyID:
853 case Type::PPC_FP128TyID:
854 ReplaceCallWith("sqrtl", CI, CI->op_begin()+1, CI->op_end(),
855 CI->getOperand(1)->getType(), sqrtLDCache);
860 case Intrinsic::flt_rounds:
861 // Lower to "round to the nearest"
862 if (CI->getType() != Type::VoidTy)
863 CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
867 assert(CI->use_empty() &&
868 "Lowering should have eliminated any uses of the intrinsic call!");
869 CI->eraseFromParent();