@@ -2030,9 +2030,17 @@ struct DSEState {
20302030 if (!InnerCallee)
20312031 return false ;
20322032 LibFunc Func;
2033+ StringRef ZeroedVariantName;
20332034 if (!TLI.getLibFunc (*InnerCallee, Func) || !TLI.has (Func) ||
2034- Func != LibFunc_malloc)
2035- return false ;
2035+ Func != LibFunc_malloc) {
2036+ Attribute Attr = Malloc->getFnAttr (" alloc-variant-zeroed" );
2037+ if (!Attr.isValid ())
2038+ return false ;
2039+ ZeroedVariantName = Attr.getValueAsString ();
2040+ if (ZeroedVariantName.empty ())
2041+ return false ;
2042+ }
2043+
20362044 // Gracefully handle malloc with unexpected memory attributes.
20372045 auto *MallocDef = dyn_cast_or_null<MemoryDef>(MSSA.getMemoryAccess (Malloc));
20382046 if (!MallocDef)
@@ -2059,15 +2067,32 @@ struct DSEState {
20592067
20602068 if (Malloc->getOperand (0 ) != MemSet->getLength ())
20612069 return false ;
2062- if (!shouldCreateCalloc (Malloc, MemSet) ||
2063- !DT.dominates (Malloc, MemSet) ||
2070+ if (!shouldCreateCalloc (Malloc, MemSet) || !DT.dominates (Malloc, MemSet) ||
20642071 !memoryIsNotModifiedBetween (Malloc, MemSet, BatchAA, DL, &DT))
20652072 return false ;
20662073 IRBuilder<> IRB (Malloc);
2067- Type *SizeTTy = Malloc->getArgOperand (0 )->getType ();
2068- auto *Calloc =
2069- emitCalloc (ConstantInt::get (SizeTTy, 1 ), Malloc->getArgOperand (0 ), IRB,
2070- TLI, Malloc->getType ()->getPointerAddressSpace ());
2074+ assert (Func == LibFunc_malloc || !ZeroedVariantName.empty ());
2075+ Value *Calloc = nullptr ;
2076+ if (!ZeroedVariantName.empty ()) {
2077+ LLVMContext &Ctx = Malloc->getContext ();
2078+ AttributeList Attrs = InnerCallee->getAttributes ();
2079+ AllocFnKind AllocKind =
2080+ Attrs.getFnAttr (Attribute::AllocKind).getAllocKind () |
2081+ AllocFnKind::Zeroed;
2082+ Attrs =
2083+ Attrs.addFnAttribute (Ctx, Attribute::getWithAllocKind (Ctx, AllocKind))
2084+ .removeFnAttribute (Ctx, " alloc-variant-zeroed" );
2085+ FunctionCallee ZeroedVariant = Malloc->getModule ()->getOrInsertFunction (
2086+ ZeroedVariantName, InnerCallee->getFunctionType (), Attrs);
2087+ SmallVector<Value *, 3 > Args;
2088+ Args.append (Malloc->arg_begin (), Malloc->arg_end ());
2089+ Calloc = IRB.CreateCall (ZeroedVariant, Args, ZeroedVariantName);
2090+ } else {
2091+ Type *SizeTTy = Malloc->getArgOperand (0 )->getType ();
2092+ Calloc =
2093+ emitCalloc (ConstantInt::get (SizeTTy, 1 ), Malloc->getArgOperand (0 ),
2094+ IRB, TLI, Malloc->getType ()->getPointerAddressSpace ());
2095+ }
20712096 if (!Calloc)
20722097 return false ;
20732098
0 commit comments