Reapply address space patch after fixing an issue in MemCopyOptimizer.
[oota-llvm.git] / lib / Transforms / Utils / BuildLibCalls.cpp
1 //===- BuildLibCalls.cpp - Utility builder for libcalls -------------------===//
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 some functions that will create standard C libcalls.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Transforms/Utils/BuildLibCalls.h"
15 #include "llvm/Type.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Function.h"
18 #include "llvm/Module.h"
19 #include "llvm/Support/IRBuilder.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Intrinsics.h"
23
24 using namespace llvm;
25
26 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
27 Value *llvm::CastToCStr(Value *V, IRBuilder<> &B) {
28   return B.CreateBitCast(V, B.getInt8PtrTy(), "cstr");
29 }
30
31 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
32 /// specified pointer.  This always returns an integer value of size intptr_t.
33 Value *llvm::EmitStrLen(Value *Ptr, IRBuilder<> &B, const TargetData *TD) {
34   Module *M = B.GetInsertBlock()->getParent()->getParent();
35   AttributeWithIndex AWI[2];
36   AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
37   AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
38                                    Attribute::NoUnwind);
39
40   LLVMContext &Context = B.GetInsertBlock()->getContext();
41   Constant *StrLen = M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
42                                             TD->getIntPtrType(Context),
43                                             B.getInt8PtrTy(),
44                                             NULL);
45   CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
46   if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
47     CI->setCallingConv(F->getCallingConv());
48
49   return CI;
50 }
51
52 /// EmitStrChr - Emit a call to the strchr function to the builder, for the
53 /// specified pointer and character.  Ptr is required to be some pointer type,
54 /// and the return value has 'i8*' type.
55 Value *llvm::EmitStrChr(Value *Ptr, char C, IRBuilder<> &B,
56                         const TargetData *TD) {
57   Module *M = B.GetInsertBlock()->getParent()->getParent();
58   AttributeWithIndex AWI =
59     AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
60
61   const Type *I8Ptr = B.getInt8PtrTy();
62   const Type *I32Ty = B.getInt32Ty();
63   Constant *StrChr = M->getOrInsertFunction("strchr", AttrListPtr::get(&AWI, 1),
64                                             I8Ptr, I8Ptr, I32Ty, NULL);
65   CallInst *CI = B.CreateCall2(StrChr, CastToCStr(Ptr, B),
66                                ConstantInt::get(I32Ty, C), "strchr");
67   if (const Function *F = dyn_cast<Function>(StrChr->stripPointerCasts()))
68     CI->setCallingConv(F->getCallingConv());
69   return CI;
70 }
71
72 /// EmitStrCpy - Emit a call to the strcpy function to the builder, for the
73 /// specified pointer arguments.
74 Value *llvm::EmitStrCpy(Value *Dst, Value *Src, IRBuilder<> &B,
75                         const TargetData *TD, StringRef Name) {
76   Module *M = B.GetInsertBlock()->getParent()->getParent();
77   AttributeWithIndex AWI[2];
78   AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
79   AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
80   const Type *I8Ptr = B.getInt8PtrTy();
81   Value *StrCpy = M->getOrInsertFunction(Name, AttrListPtr::get(AWI, 2),
82                                          I8Ptr, I8Ptr, I8Ptr, NULL);
83   CallInst *CI = B.CreateCall2(StrCpy, CastToCStr(Dst, B), CastToCStr(Src, B),
84                                Name);
85   if (const Function *F = dyn_cast<Function>(StrCpy->stripPointerCasts()))
86     CI->setCallingConv(F->getCallingConv());
87   return CI;
88 }
89
90 /// EmitStrNCpy - Emit a call to the strncpy function to the builder, for the
91 /// specified pointer arguments.
92 Value *llvm::EmitStrNCpy(Value *Dst, Value *Src, Value *Len,
93                          IRBuilder<> &B, const TargetData *TD) {
94   Module *M = B.GetInsertBlock()->getParent()->getParent();
95   AttributeWithIndex AWI[2];
96   AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
97   AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
98   const Type *I8Ptr = B.getInt8PtrTy();
99   Value *StrNCpy = M->getOrInsertFunction("strncpy", AttrListPtr::get(AWI, 2),
100                                          I8Ptr, I8Ptr, I8Ptr,
101                                          Len->getType(), NULL);
102   CallInst *CI = B.CreateCall3(StrNCpy, CastToCStr(Dst, B), CastToCStr(Src, B),
103                                Len, "strncpy");
104   if (const Function *F = dyn_cast<Function>(StrNCpy->stripPointerCasts()))
105     CI->setCallingConv(F->getCallingConv());
106   return CI;
107 }
108
109
110 /// EmitMemCpy - Emit a call to the memcpy function to the builder.  This always
111 /// expects that Len has type 'intptr_t' and Dst/Src are pointers.
112 Value *llvm::EmitMemCpy(Value *Dst, Value *Src, Value *Len, unsigned Align,
113                         bool isVolatile, IRBuilder<> &B, const TargetData *TD) {
114   Module *M = B.GetInsertBlock()->getParent()->getParent();
115   const Type *ArgTys[3] = { Dst->getType(), Src->getType(), Len->getType() };
116   Value *MemCpy = Intrinsic::getDeclaration(M, Intrinsic::memcpy, ArgTys, 3);
117   Dst = CastToCStr(Dst, B);
118   Src = CastToCStr(Src, B);
119   return B.CreateCall5(MemCpy, Dst, Src, Len,
120                        ConstantInt::get(B.getInt32Ty(), Align),
121                        ConstantInt::get(B.getInt1Ty(), isVolatile));
122 }
123
124 /// EmitMemCpyChk - Emit a call to the __memcpy_chk function to the builder.
125 /// This expects that the Len and ObjSize have type 'intptr_t' and Dst/Src
126 /// are pointers.
127 Value *llvm::EmitMemCpyChk(Value *Dst, Value *Src, Value *Len, Value *ObjSize,
128                            IRBuilder<> &B, const TargetData *TD) {
129   Module *M = B.GetInsertBlock()->getParent()->getParent();
130   AttributeWithIndex AWI;
131   AWI = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
132   LLVMContext &Context = B.GetInsertBlock()->getContext();
133   Value *MemCpy = M->getOrInsertFunction("__memcpy_chk",
134                                          AttrListPtr::get(&AWI, 1),
135                                          B.getInt8PtrTy(),
136                                          B.getInt8PtrTy(),
137                                          B.getInt8PtrTy(),
138                                          TD->getIntPtrType(Context),
139                                          TD->getIntPtrType(Context), NULL);
140   Dst = CastToCStr(Dst, B);
141   Src = CastToCStr(Src, B);
142   CallInst *CI = B.CreateCall4(MemCpy, Dst, Src, Len, ObjSize);
143   if (const Function *F = dyn_cast<Function>(MemCpy->stripPointerCasts()))
144     CI->setCallingConv(F->getCallingConv());
145   return CI;
146 }
147
148 /// EmitMemMove - Emit a call to the memmove function to the builder.  This
149 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
150 Value *llvm::EmitMemMove(Value *Dst, Value *Src, Value *Len, unsigned Align,
151                          bool isVolatile, IRBuilder<> &B, const TargetData *TD) {
152   Module *M = B.GetInsertBlock()->getParent()->getParent();
153   LLVMContext &Context = B.GetInsertBlock()->getContext();
154   const Type *ArgTys[3] = { Dst->getType(), Src->getType(),
155                             TD->getIntPtrType(Context) };
156   Value *MemMove = Intrinsic::getDeclaration(M, Intrinsic::memmove, ArgTys, 3);
157   Dst = CastToCStr(Dst, B);
158   Src = CastToCStr(Src, B);
159   Value *A = ConstantInt::get(B.getInt32Ty(), Align);
160   Value *Vol = ConstantInt::get(B.getInt1Ty(), isVolatile);
161   return B.CreateCall5(MemMove, Dst, Src, Len, A, Vol);
162 }
163
164 /// EmitMemChr - Emit a call to the memchr function.  This assumes that Ptr is
165 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
166 Value *llvm::EmitMemChr(Value *Ptr, Value *Val,
167                         Value *Len, IRBuilder<> &B, const TargetData *TD) {
168   Module *M = B.GetInsertBlock()->getParent()->getParent();
169   AttributeWithIndex AWI;
170   AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
171   LLVMContext &Context = B.GetInsertBlock()->getContext();
172   Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
173                                          B.getInt8PtrTy(),
174                                          B.getInt8PtrTy(),
175                                          B.getInt32Ty(),
176                                          TD->getIntPtrType(Context),
177                                          NULL);
178   CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
179
180   if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
181     CI->setCallingConv(F->getCallingConv());
182
183   return CI;
184 }
185
186 /// EmitMemCmp - Emit a call to the memcmp function.
187 Value *llvm::EmitMemCmp(Value *Ptr1, Value *Ptr2,
188                         Value *Len, IRBuilder<> &B, const TargetData *TD) {
189   Module *M = B.GetInsertBlock()->getParent()->getParent();
190   AttributeWithIndex AWI[3];
191   AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
192   AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
193   AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
194                                    Attribute::NoUnwind);
195
196   LLVMContext &Context = B.GetInsertBlock()->getContext();
197   Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
198                                          B.getInt32Ty(),
199                                          B.getInt8PtrTy(),
200                                          B.getInt8PtrTy(),
201                                          TD->getIntPtrType(Context), NULL);
202   CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
203                                Len, "memcmp");
204
205   if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
206     CI->setCallingConv(F->getCallingConv());
207
208   return CI;
209 }
210
211 /// EmitMemSet - Emit a call to the memset function
212 Value *llvm::EmitMemSet(Value *Dst, Value *Val, Value *Len, bool isVolatile,
213                         IRBuilder<> &B, const TargetData *TD) {
214  Module *M = B.GetInsertBlock()->getParent()->getParent();
215  Intrinsic::ID IID = Intrinsic::memset;
216  const Type *Tys[2] = { Dst->getType(), Len->getType() };
217  Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 2);
218  Value *Align = ConstantInt::get(B.getInt32Ty(), 1);
219  Value *Vol = ConstantInt::get(B.getInt1Ty(), isVolatile);
220  return B.CreateCall5(MemSet, CastToCStr(Dst, B), Val, Len, Align, Vol);
221 }
222
223 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
224 /// 'floor').  This function is known to take a single of type matching 'Op' and
225 /// returns one value with the same type.  If 'Op' is a long double, 'l' is
226 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
227 Value *llvm::EmitUnaryFloatFnCall(Value *Op, const char *Name,
228                                   IRBuilder<> &B, const AttrListPtr &Attrs) {
229   char NameBuffer[20];
230   if (!Op->getType()->isDoubleTy()) {
231     // If we need to add a suffix, copy into NameBuffer.
232     unsigned NameLen = strlen(Name);
233     assert(NameLen < sizeof(NameBuffer)-2);
234     memcpy(NameBuffer, Name, NameLen);
235     if (Op->getType()->isFloatTy())
236       NameBuffer[NameLen] = 'f';  // floorf
237     else
238       NameBuffer[NameLen] = 'l';  // floorl
239     NameBuffer[NameLen+1] = 0;
240     Name = NameBuffer;
241   }
242
243   Module *M = B.GetInsertBlock()->getParent()->getParent();
244   Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
245                                          Op->getType(), NULL);
246   CallInst *CI = B.CreateCall(Callee, Op, Name);
247   CI->setAttributes(Attrs);
248   if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
249     CI->setCallingConv(F->getCallingConv());
250
251   return CI;
252 }
253
254 /// EmitPutChar - Emit a call to the putchar function.  This assumes that Char
255 /// is an integer.
256 Value *llvm::EmitPutChar(Value *Char, IRBuilder<> &B, const TargetData *TD) {
257   Module *M = B.GetInsertBlock()->getParent()->getParent();
258   Value *PutChar = M->getOrInsertFunction("putchar", B.getInt32Ty(),
259                                           B.getInt32Ty(), NULL);
260   CallInst *CI = B.CreateCall(PutChar,
261                               B.CreateIntCast(Char,
262                               B.getInt32Ty(),
263                               /*isSigned*/true,
264                               "chari"),
265                               "putchar");
266
267   if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
268     CI->setCallingConv(F->getCallingConv());
269   return CI;
270 }
271
272 /// EmitPutS - Emit a call to the puts function.  This assumes that Str is
273 /// some pointer.
274 void llvm::EmitPutS(Value *Str, IRBuilder<> &B, const TargetData *TD) {
275   Module *M = B.GetInsertBlock()->getParent()->getParent();
276   AttributeWithIndex AWI[2];
277   AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
278   AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
279
280   Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
281                                        B.getInt32Ty(),
282                                        B.getInt8PtrTy(),
283                                        NULL);
284   CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
285   if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
286     CI->setCallingConv(F->getCallingConv());
287
288 }
289
290 /// EmitFPutC - Emit a call to the fputc function.  This assumes that Char is
291 /// an integer and File is a pointer to FILE.
292 void llvm::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B,
293                      const TargetData *TD) {
294   Module *M = B.GetInsertBlock()->getParent()->getParent();
295   AttributeWithIndex AWI[2];
296   AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
297   AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
298   Constant *F;
299   if (File->getType()->isPointerTy())
300     F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2),
301                                B.getInt32Ty(),
302                                B.getInt32Ty(), File->getType(),
303                                NULL);
304   else
305     F = M->getOrInsertFunction("fputc",
306                                B.getInt32Ty(),
307                                B.getInt32Ty(),
308                                File->getType(), NULL);
309   Char = B.CreateIntCast(Char, B.getInt32Ty(), /*isSigned*/true,
310                          "chari");
311   CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
312
313   if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
314     CI->setCallingConv(Fn->getCallingConv());
315 }
316
317 /// EmitFPutS - Emit a call to the puts function.  Str is required to be a
318 /// pointer and File is a pointer to FILE.
319 void llvm::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B,
320                      const TargetData *TD) {
321   Module *M = B.GetInsertBlock()->getParent()->getParent();
322   AttributeWithIndex AWI[3];
323   AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
324   AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
325   AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
326   Constant *F;
327   if (File->getType()->isPointerTy())
328     F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3),
329                                B.getInt32Ty(),
330                                B.getInt8PtrTy(),
331                                File->getType(), NULL);
332   else
333     F = M->getOrInsertFunction("fputs", B.getInt32Ty(),
334                                B.getInt8PtrTy(),
335                                File->getType(), NULL);
336   CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
337
338   if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
339     CI->setCallingConv(Fn->getCallingConv());
340 }
341
342 /// EmitFWrite - Emit a call to the fwrite function.  This assumes that Ptr is
343 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
344 void llvm::EmitFWrite(Value *Ptr, Value *Size, Value *File,
345                       IRBuilder<> &B, const TargetData *TD) {
346   Module *M = B.GetInsertBlock()->getParent()->getParent();
347   AttributeWithIndex AWI[3];
348   AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
349   AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
350   AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
351   LLVMContext &Context = B.GetInsertBlock()->getContext();
352   Constant *F;
353   if (File->getType()->isPointerTy())
354     F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
355                                TD->getIntPtrType(Context),
356                                B.getInt8PtrTy(),
357                                TD->getIntPtrType(Context),
358                                TD->getIntPtrType(Context),
359                                File->getType(), NULL);
360   else
361     F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(Context),
362                                B.getInt8PtrTy(),
363                                TD->getIntPtrType(Context),
364                                TD->getIntPtrType(Context),
365                                File->getType(), NULL);
366   CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
367                         ConstantInt::get(TD->getIntPtrType(Context), 1), File);
368
369   if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
370     CI->setCallingConv(Fn->getCallingConv());
371 }
372
373 SimplifyFortifiedLibCalls::~SimplifyFortifiedLibCalls() { }
374
375 bool SimplifyFortifiedLibCalls::fold(CallInst *CI, const TargetData *TD) {
376   this->CI = CI;
377   StringRef Name = CI->getCalledFunction()->getName();
378   BasicBlock *BB = CI->getParent();
379   IRBuilder<> B(CI->getParent()->getContext());
380
381   // Set the builder to the instruction after the call.
382   B.SetInsertPoint(BB, CI);
383
384   if (Name == "__memcpy_chk") {
385     if (isFoldable(4, 3, false)) {
386       EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
387                  1, false, B, TD);
388       replaceCall(CI->getOperand(1));
389       return true;
390     }
391     return false;
392   }
393
394   // Should be similar to memcpy.
395   if (Name == "__mempcpy_chk") {
396     return false;
397   }
398
399   if (Name == "__memmove_chk") {
400     if (isFoldable(4, 3, false)) {
401       EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
402                   1, false, B, TD);
403       replaceCall(CI->getOperand(1));
404       return true;
405     }
406     return false;
407   }
408
409   if (Name == "__memset_chk") {
410     if (isFoldable(4, 3, false)) {
411       Value *Val = B.CreateIntCast(CI->getOperand(2), B.getInt8Ty(),
412                                    false);
413       EmitMemSet(CI->getOperand(1), Val,  CI->getOperand(3), false, B, TD);
414       replaceCall(CI->getOperand(1));
415       return true;
416     }
417     return false;
418   }
419
420   if (Name == "__strcpy_chk" || Name == "__stpcpy_chk") {
421     // If a) we don't have any length information, or b) we know this will
422     // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
423     // st[rp]cpy_chk call which may fail at runtime if the size is too long.
424     // TODO: It might be nice to get a maximum length out of the possible
425     // string lengths for varying.
426     if (isFoldable(3, 2, true)) {
427       Value *Ret = EmitStrCpy(CI->getOperand(1), CI->getOperand(2), B, TD,
428                               Name.substr(2, 6));
429       replaceCall(Ret);
430       return true;
431     }
432     return false;
433   }
434
435   if (Name == "__strncpy_chk") {
436     if (isFoldable(4, 3, false)) {
437       Value *Ret = EmitStrNCpy(CI->getOperand(1), CI->getOperand(2),
438                                CI->getOperand(3), B, TD);
439       replaceCall(Ret);
440       return true;
441     }
442     return false;
443   }
444
445   if (Name == "__strcat_chk") {
446     return false;
447   }
448
449   if (Name == "__strncat_chk") {
450     return false;
451   }
452
453   return false;
454 }